简体   繁体   中英

what is the output of this code in C?

I found this code in page no. 127 of this Book writer says it print 42. But when i try this it prints some garbage value. Why this is so?

    #include <stdio.h>
    void foo()
    {
        int a ;
        printf("%d \n", a);
    }

    void bar()
    {
        int a = 42;
    }

    int main()
    {
        bar();
        foo();
        return 0;
    }

a in foo() is uninitialized, so it's undefined behavior.

However, in practice, some compilers actually do output 42 (especially if optimization is off). That's because after the call of bar() , the value 42 is left in the stack. And inside foo() , the uninitialized a gets it. Again, it's undefined behavior so anything may happen, just don't do it.

In foo() the variable a is uninitialized. Printing such a variable is garbage. The function bar() has no meaning at all - and is likely removed from the optimizer during compile time.

a in function foo is a local variable of this function and in function bar is also a local variable and it has nothing to do with function bar's a

so when you assign a value to a in function bar there is no changes in a of function foo since then you see garbage value when you print a in foo

The value of a defined in bar() is only in scope for the duration of that function. When a is defined again in foo() the compiler reassigns a and you have no guarantee what the memory stores. You can't assume that it will overwrite the original a and point to 42.

The way to get the function to print 42 would be to define a in main(), then set a=42 in bar() and get rid of the redefinition in foo().

Are sure you haven't copied out a counter example? Either that or you should treat your book with suspicion from now on.

The answer of Yu Hao explains it the best way, I want to modify your code such that it (works):

#include <stdio.h>
void foo(int a)
{
    printf("%d \n", a);
}

void bar(int *a)
{
    *a = 42;
}

int main()
{
    int b;
    bar(&b);
    foo(b);
    return 0;
}

The value of a is uninitialized in foo() function. if the heap stack in runtime memory is emty, then it will print garbage value, else print the first existed value. You can thange the foo() to:

void foo()
{
    int d ;
    printf("%d \n", d);

    int e ;
    printf("%d \n", e);
}

the sencond line will print garbage value, such as 124992. So the result is relate to the heap stack in runtime memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM