Why do uninitialized “max” and “min” values work on Linux but not Windows? For example:
double max, min, test;
while (1)
{
std::cin >> test;
if (test > max)
max = test;
if (test < min)
min = test;
}
This works on Linux. I know for a fact because I’ve been using this (although I didn’t realize until now how terrible this is) for at least 3 months now. However, I’ve been told by a number of co-workers that this is broken on their machines: They compile using Visual Studio. Is there some validity to their statements, and why? Is this simply a case of UB? If so, how has it been working for the past months without me noticing?
Also note: gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2 and Visual Studio 2010
Roughly speaking, your code will appear to work if the uninitialized variables
minandmaxjust so happen to hold values that compare in between the actual minimum and maximum values encountered intest. The object representation of an uninitialized automatic variable may or may not be consistent, depending on compiler, options, and the code in the rest of the program. Reading an uninitialized value is certainly UB. UB may or may not be consistent.So for example, one simple way that you could get the behavior you observe is if:
test < minandtest > maxare both always false).Depending on what your test data is, and what “broken on their machines” means, the details may be different. I’ve just described one possibility out of the infinite scope of UB.