Tutorial :What is the default state of variables?



Question:

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?


Solution:1

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.


Solution:2

Edit: The following only applies to local variables - not globals.

The initial value of a variable is undefined. In some languages a variable's location in memory is zero'd out upon declaration but in C (and C++ as well) an uninitialized variable will contain whatever garbage that lives at that location at that time.

So the best way to think of it is that an uninitialized variable will most likely contain garbage and have undefined behavior.


Solution:3

a will be zero, and c too, if they are global and not explicitly initialized. This is also true for local static variables.

Only local non-static variables are not initialized. Also memory allocated with malloc is not initialized.

See here for rules of initializations and allocation in C for the different objects.


Solution:4

I'm typing way too slowly this morning. Three people popped in quickly as I was answering, so I've removed most of my post. The link I found was clear and brief, so I'm posting that anyhow: Wikipedia on "uninitialized variable" for a discussion of the basic issues.


Solution:5

A quick test shows a and c to be 0.

int a;  static int c;  int main() {      printf("%d %d\n", a, c);      return 0;  }  

The location of a (and c) are determined at compile-time; that is, they're neither put on the stack nor in a memory interval returned by malloc. I think the C standard says they're initialized to 0 in all cases, then.

I'm 99.9% confident about with respect to c, and 98% confident with regard to a. The keyword static, in the context of global variables, really is analogous to private in (say) C++ and Java: it's about visibility, not storage location.

What Andrew Hare says about uninitialized variables is true for data stored on the stack or in malloc'd memory. Not so for statically stored variables.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »