Search code examples
cgarbage

Why automatic variable will contain garbage if it is not set?


In 'The C programming language' third edition and on p.32 I saw those lines which make me confused:

Because automatic variables come and go with function invocation, they do not retain their values from one call to the next, and must be explicitly set upon each entry. If they are not set, they will contain garbage

Is it saying that for the following code, a will not contain garbage after the program finished its execution and if I declare a like this: int a; then a will contain garbage?

#include <stdio.h>
int main () {
        int a = 5;
        // int a;
        printf("\n\t %d", a);
}

Solution

  • Using the value of a not initialised variable is undefined behaviour. In practice automatic variables are allocated in processor registers or on the stack. Normally if not initialised they will get the value present in the register or memory used for the stack at the moment. So e.g. an int variable may contain a part of memory which was double variable in a function called just a moment ago. In other words the value is random.