Local int vs Global int in C

  • A+
Category:Languages

I read that:

in C, local variables start with unknown value

and I decided to check it, that's what I did:

Three results of the same program: 1, 2, 3.

Question 1: Why unknown value in 1, or why global int was 0 and local int was 1?

Question 2: Why local unsigned int with each new start was different?

Question 3: Is global/local char ' '? char ch = ' '; // something like that

Question 4: Why global and local start with different values (if they are not initialised)? For what?

Source code: (I used clang (v10.0.0) for compiling)

#include <stdio.h>  int global_int; unsigned int global_unsint; char global_char;  int main() {   int local_int;   unsigned int local_unsint;   char local_char;    printf ("Global int: %d /t unsigned_int: %u /t char: %c/n", global_int, global_unsint, global_char);   printf ("Local int: %d /t unsigned_int: %u /t char: %c/n", local_int, local_unsint, local_char);  } 

 


local variables start with unknown value

Not entirely true. Local variables with automatic storage duration do; static variables are initialized at zero. As it happens, all the local variables in main() in your code snippet have automatic storage duration.

Why unknown value it's 1, or why global int was 0 and local int was 1?

Global variables have static storage duration. This means they are implicitly initialized at zero on program startup. Local variables with automatic storage duration have undefined values until they are explicitly initialized.

Why local unsigned_int with each new start was different?

That's undefined behavior for you. All bets are off.

Is global/local char was ' ' ?

No. The global char is implicitly initialized as '/0' on program startup; the local char has an undefined value.

Why global and local start with different values (if they are not initialised)? For what?

Because of rules for initialization of objects with static storage duration and automatic storage duration.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: