[LLVMdev] Uninitialized variable - question
Nick Lewycky
nicholas at mxc.ca
Sat Nov 24 03:21:57 PST 2012
On 11/24/2012 02:08 AM, Jakub Staszak wrote:
> Hello,
>
> I was wondering about the case below. I tried to find any information in C standard, but I found nothing.
> In this case, variable "i" is uninitialized, but it is the _same_ value passed as an argument, so only of "a" or "b" should be printed.
>
> What I found is that with -O2:
> LLVM (trunk) prints both "a" and "b"
> GCC (4.2) prints both "a" and "b"
> GCC (trunk) prints "b" only.
>
> As I said, I don't know what standard says here.
>
>
> #include<stdio.h>
>
> void f(int i) __attribute__((noinline));
> void g(int i) __attribute__((noinline));
>
> void f(int i) {
> if (i) printf("a\n");
> }
>
> void g(int i) {
> if (!i) printf("b\n");
> }
>
> int main() {
> int i;
> f(i);
> g(i);
> }
Passing an uninitialized value as a function argument is undefined
behaviour on the spot, regardless of what the callee does (even if it
never references that argument).
That aside, there is no way that 'i' has the same value, since it has no
value. This:
int i;
printf("%d\n", i);
printf("%d\n", i);
is allowed to print two different values (or, applying the above rule,
format your hard drive). The way the standard defines the behaviour that
you see when reading a value is by stating that it must have the value
that was last stored in it. When no value was stored, there are no rules
to apply about what you get each time you look at it, and there is no
other guarantee of a consistent value anywhere in the standard. This
rule permits your program to print both 'a' and 'b', or neither.
I should mention that the above is for C++, and I don't have a copy of
any of the standards handy, but I expect the rules to be the same for C
and C++ here.
Nick
More information about the llvm-dev
mailing list