简体   繁体   中英

Simple C program, weird output

In this simple C program, when I comment Line Y and leave Line X as is, the output of the call to f() outputs 0 and Line B outputs some random number. When I comment Line X and uncomment Line Y , then the output is some random number because of Line B and another random number because of Line Y . However, when I comment Line A and Line B , both calls to f() output 0 . Can someone explain to me why this is the case? Thank you in advance. By the way, I'm using gcc without any flags and running this on macOS Catalina.

#include <stdio.h>

void f() {
    int x;
    printf("%d\n", x);
}

int main() {
    f();               // Line X
    int a;             // Line A
    printf("%d\n", a); // Line B
    f();               // Line Y
    return 0;
}

When you do this:

int x;
printf("%d\n", x);

You are allocating space on the stack for x and then printing its value. That value could theoretically be anything (you can't expect it to be zero, or any particular value), but in practice it will be whatever value happened to be there on the stack before.

This is why changing the surrounding code changes the value of x , because the stack is used by other parts of your program, and changing those parts leaves different values sitting in that space in the stack where x happens to be allocated.

You may also get different values of x when you change compiler options, or use a different computer.

You may be wondering why removing "Line A" alters the output of "Line X" which comes before "Line A." That is because the compiler may do all stack allocations for main at the start of the function instead of line-by-line (eg it allocates space for a before x , thus altering the value you see when you print x , because it has shifted "down" one space on the stack).

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