immi101: I don't think it is legal. But I guess the code gets optimized away before it even has a chance to throw an error.
Alaric.us: The weirdest part is not even
int x = x; Since it does nothing at all, it
could technically be ignored by the compiler altogether. What is weird, is this:
printf(x); Even if the previous line is ignored somehow, this should definitely throw an error.
In the code I posted, I did not include the line
#include<stdio.h>
therefore, the compiler doesn't see the prototype for printf and therefore is unable to check to make sure the first argument is a pointer to a constant character. Hence, the value of x is passed as the first argument to printf. In this example, x seems to have a value of 0 (which, as a pointer, would be NULL), and glibc printf simply prints nothing if the first argument to printf is NULL. (Don't count on this behavior; a different printf implementation could segfault in this instant.) I note that gcc does have special logic that causes it to emit a warning at compile time when the arguments to printf are wrong, like in this case, so at least we get a warning here.
If I instead use the line
printf("%d\n", x);
in there, it prints 0, suggesting that, in this case, x happened to be initialized to 0, but don't count on this behavior.
Note that much of this behavior is actually undefined in the standard, so a compiler is allowed to do literally anything.
Yes, C sometimes allows things it clearly shouldn't.