Same piece of C code behaving differently...

Hi,

Here is two pieces of C code both behaves differently,
could someone explain me the reason please.

1. Loops only once and exits.

int x =0;
int ind;

while (1)
{
x += 1;
if (x == 10) ind = 1;

........
.......
.....

if (ind) break;
}


2. Loops 10 times, only difference is has got printf statement.

int x =0;
int ind;

while (1)
{
x += 1;
printf("x is %d\n",x);
if (x == 10) ind = 1;

........
.......
.....

if (ind) break;
}


But the actual mistake in the code is i've not initialized variable "ind",even though it works fine when I put printf statement in it.

Please explain me the reason, do printf statement resets the uninitialized variables...?

Any suggestion is appreciated.

Regards,
Vishwanath
Neither printf() nor any other function will, as a side-effect, reset uninitialized variables. The C++ standard does not guarantee the behavior of uninitialized variables, so your code is "taking advantage" of behavior that is undefined by the standard. Said another way, you shouldn't need to be concerned about why it behaves differently in the two cases because neither is correct since there is no definition of "correct" in this case.

It you really want to know why, you would probably need to look at the assembler code generated by the compiler to understand why in one case the variable always seems to be non-zero and in the other always seems to be zero.
Topic archived. No new replies allowed.