Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local int vs Global int in C

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); 
}
like image 267
jstusr Avatar asked Dec 13 '22 12:12

jstusr


2 Answers

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.

like image 194
Govind Parmar Avatar answered Dec 28 '22 22:12

Govind Parmar


Accessing uninitialized (or previously unassigned) variable invokes Undefined Behavior.

Anything can happen; for example

  • your compiler may produce an executable
  • your executable may "run"
  • running your executable may appear to work as expected
  • the values printed may be reasoned for

or none of the above, depending on the phase of the moon, the compiler flags, what other programs are running on your computer at the same time, ..., ..., ...

like image 32
pmg Avatar answered Dec 28 '22 21:12

pmg