Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default state of variables?

When a C program starts and variables are assigned to memory locations, does the C standard say if that value is initialized?

// global variables
int a;
int b = 0;
static int c;

In the above code, 'b' will be initialized to 0. What is the initial value of 'a'? Is 'c' any different since it is static to this module?

like image 219
Robert Avatar asked Nov 29 '22 20:11

Robert


1 Answers

Since you specifically mention global variables: In the case of global variables, whether they are declared static or not, they will be initialised to 0.

Local variables on the other hand will be undefined (unless they are declared static, in which case they too will be initialised to 0 -- thanks Tyler McHenry). Translated, that means that you can't rely on them containing any particular thing -- they will just contain whatever random garbage was already in memory at that location, which could be different from run to run.

like image 99
j_random_hacker Avatar answered Dec 04 '22 20:12

j_random_hacker