Tee
Tee

Reputation: 55

Default values of uninitialized local variables in C

Im trying to get my head around declaration and definition of variables in C. My learning material from school says that global uninitialised variables are assigned 0 whereas uninitialised local variables are left unassigned and have a value that was present in that memory address.

However, I tried a following very simple program:

#include <stdio.h>

void something(){

    int third;
    int fourth;

    printf("third: %d\n", third);
    printf("fourth: %d\n", fourth);
}

int main(){
    int first;
    int second;

    printf("first: %d\n",first);
    printf("second: %d\n",second);
    something();
    return 0;
}

Output is following:

first: 382501330
second: 32766
third: 0
fourth: 0

Second run:

first: 235426258
second: 32766
third: 0
fourth: 0

Observations:

Upvotes: 3

Views: 497

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60056

You're accessing uninitialized locals that could have been declared register. That's undefined behavior. Your program no longer makes sense.

If you fix it up by sprinkling in some & operators (so that the locals no longer can have been declared register)

#include <stdio.h>

void something(){

    int third;
    int fourth;

    printf("third: %d\n", *&third);
    printf("fourth: %d\n", *&fourth);
}

int main(){
    int first;
    int second;

    printf("first: %d\n", *&first);
    printf("second: %d\n", *&second);
    something();
    return 0;
}

then as far as C is concerned the values will be unspecified. What you'll get depends on your environemnt and what the main-calling libc-routine left in the stack before it made the call to main.

Upvotes: 2

Related Questions