views:

89

answers:

3

Hi.

#include <stdio.h>

main()
{
    int a;
    for(a=1; a<=4 && printf("%d ",a); a++)
    {
       int a;
       static int b=a;
       printf("%d ",(a++)-b);
    }  
    getchar();
    getchar(); 
}  

In this code, the printout is 1 0 2 1 3 2 4 3. I understand why the int a; part works differently than the int a which was defined outside the for function, and why static int b; is only defined once with the primary value of a ; but why does the (a++) part in printf affect proceeding values of a? Don't we redefine int a; each time the for function runs? Thanks in advance.

+3  A: 

the inner 'a' variable is uninitialized, so it's value is technically undefined each time through the loop.

vicatcu
I know it is uninitialized, but I see that the uninitialized value of a increases with a++ in the printf function. Is this because of my compiler or is it in C++ language to be able to change the "uninitialization" value?
Kaan Tekelioglu
See James' answer. It's exactly correct.
JayM
+3  A: 

You don't assign a value to the inner a so the result is undefined.

Even if you change your code to assign something to a, your code should not be able to compile because you try to assign a variable to a local static on this line:

static int b=a;

Compiler output:

test.c: In function `main':
test.c:9: error: initializer element is not constant
Mark Byers
Wow, I didn't even realize this was invalid in C. One more reason to use C++ even if you only use C-style coding.
Dan Olson
+4  A: 

The inner a is undefined, and as such, the compiler can use any value it likes. The value it likes is apparently the current value of the bytes "a" is occupying. The second time through the loop, you get a brand new inner-a, which just coincidentally happens to be in the same location as the previous inner-A and assumes it's value.

But the is merely coincidental --- if it were easier to do it some other way, the compiler would (and legally could).

Note also, that the value of a is never read after the second a++. It's quite possible that if you turn optimizations on, the compiler will decide that it doesn't need to do that increment, and the inner value of a will always be zero.

James Curran