user6394019
user6394019

Reputation: 121

Clarification on initial value of some variable belongs to the storage class 'auto' in C

In C it is stated that a variable that belongs to 'auto-class' has an initial value. This initial value is a garbage value, however, I can't understand why it is an a garbage value, nor do I think I really understand the true concept of "Garbage Value".

#include <stdio.h>

int main(void) {
int my_int;
printf("%d", my_int);
int t;
printf("%d",t);

return 0;
}

This code leads to an answer of "00" which means that the initial value of my_int and t is "0". Can it be changed?

Upvotes: 1

Views: 110

Answers (2)

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13196

"Garbage" simply means that the value could be any possible int value. Yours happen to be zero, but purely by chance. If you ran the program at a different time, or on a different computer, different compiler settings, etc., it might be something else.

Auto storage variables are typically created by simply allocating space on the stack. That is, the stack pointer is simply adjusted by the size of the storage needed, and the contents of the memory at that location is not written to, so it contains whatever that memory previously contained from whenever it was used last. Initializing it to a specific value would require the compiler to emit code that wrote to the memory, and that takes time--C is all about speed. If you don't tell it to write to the memory, it won't bother.

Upvotes: 2

Govind Parmar
Govind Parmar

Reputation: 21572

Variables with automatic storage duration have no defined value until they are initialized. They may (and usually do) get whatever was already in memory at their address, but even this is not guaranteed. Any attempt at reasoning about undefined behavior is futile.

As for getting a value of zero every time you run your program, that also falls into undefined behavior. Undefined doesn't mean "guaranteed to be unpredictable and random on each run".

Upvotes: 1

Related Questions