1

Here's my code:

int main(){


        int age;
        int height = 72;
        // 
        double blab = (10/23242^4);


        printf("I am %d years old.\n",age);
        printf("I am %d inches tall.\n",height);

        return 0;
}

Having the blab variable makes the value of age is a random number. When I erased this variable, the value is zero, as I think the value of age was supposed to be.

alk
  • 69,737
  • 10
  • 105
  • 255
Jose A
  • 31
  • 6

2 Answers2

3

In C, variables are allocated in one of two places: globally, or on the stack. By definition, global variables are initialised to 0 if there is no assignment; stack variables are not.

int willBeZero;

void Fn(void) {
    int uninit;
    int four = 4;
} // Fn(void)

So if a stack variable is not initialised, what value does it take? What ever happens to be on the stack at that memory location, which could be 0.

If you want a particular value in a variable, you have to put it there.

John Burger
  • 3,662
  • 1
  • 13
  • 23
  • They can also be allocated to registers, and in fact scalar variables typically are when any optimization is performed. – Tom Karzes Jun 19 '16 at 05:09
2

Uninitialized local (non-static) variables have an indeterminate (and seemingly random) value. Using them without initialization leads to undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621