David Prun
David Prun

Reputation: 8453

Can I re-initialize global variable to override its value in C?

Does anyone know why my program prints -69 in below case? I expect it to print default/ garbage value of uninitialized primitive data types in C language. Thanks.

#include<stdio.h>

int a = 0; //global I get it
void doesSomething(){
   int a ; //I override global declaration to test.
   printf("I am int a : %d\n", a); //but I am aware this is not.
    a = -69; //why the function call on 2nd time prints -69?
}

int main(){
  a = 99; //I re-assign a from 0 -> 99
  doesSomething(); // I expect it to print random value of int a
  doesSomething(); // expect it to print random value, but prints -69 , why??
  int uninitialized_variable;
  printf("The uninitialized integer value is %d\n", uninitialized_variable);
}

Upvotes: 0

Views: 1220

Answers (2)

pintarj
pintarj

Reputation: 75

Yeah.. Your function reuse two times the same segment of memory.. So, the second time you call "doesSomething()", variable "a" will be still "random".. For example the following code fill call another function between the two calls and you OS will give you differen segments:

#include<stdio.h>

int a = 0; //global I get it
void doesSomething(){
   int a; //I override global declaration to test.
   printf("I am int a : %d\n", a); //but I am aware this is not.
    a = -69; //why the function call on 2nd time prints -69?
}

int main(){
  a = 99; //I re-assign a from 0 -> 99
  doesSomething(); // I expect it to print random value of int a
  printf( "edadadadaf\n" );
  doesSomething(); // expect it to print random value, but prints -69 , why??
  int uninitialized_variable;
  printf("The uninitialized integer value is %d\n", uninitialized_variable);
} 

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409482

What you have is undefined behavior, you can't predict the behavior of undefined behavior beforehand.

However it this case it's easy to understand. The local variable a in the doesSomething function is placed at a specific position on the stack, and that position does not change between calls. So what you're seeing is the previous value.

If you had called something else in between, you would have gotten different results.

Upvotes: 4

Related Questions