Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Why doesn't this end

Name: Anonymous 2010-10-31 5:35

#include <stdio.h>

main()
{

    int a;

while(a != 256)
    {putchar(a);
    a++;}
}

But if I add  a = 0;  after int a;, it ends fine?

Something to do with a variable not being initialized properly, and therefore, not being able to be compared or something?

Compiled with Code::Blocks+GCC or mingw or something. The debugger also reports no relevant issues with the initial code.

Name: Anonymous 2010-10-31 8:40

What I don't understand is why OP's loop never ends.

He does increment a, even if it's not initialized. By declaring the variable, it gets some block of memory assigned and, by not initializing it, the allocated memory is not cleared and the old value there is kept. Assume the worst - that this value is 257, and assume that an int is signed 4 bytes. By incrementing the variable in this while loop, it should reach 2^15-1 relatively quickly, overflow, wrap around to -2^15 and keep counting until it reaches 256 and terminates.

It certainly would NEVER exit if it were a char. An unsigned char will never reach 256. Instead, it wraps around at 255 back to 0 and the test in the while loop would always be true.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List