Is it okay NOT to initialize a local variable in C, if I do not use it, before it is assigned a value?

This is okay:

int i;
result = someFunc(&i);//it does not matter what value i is, it will 
                      //be assigned in the function.

where someFunc() is defined:

void someFunc(int *in)
{
    *in = 10;
}

This is not okay

int i;
int someArray[10];
int a = someArray[i];//it is not known what value 'i' is. Fault if > 9. 

But as a matter of good programming habits (maintainability, readability, proactive bug prevention), it is always a good idea to just initialize:

int i = 0;
char *tok = NULL;
char string[] = {"string"};
float array[100] = {0};
... and so on.

It is perfectly fine from program perspective not to initialize variable right away. So this:

int a;

// 10000 lines of code

// line 10001
a = 0
use(a);

is perfectly fine.

But what happens is that people (including myself) would start using that variable before line 10001 and forget that they did not initialize it, get garbage and than think that something is wrong with the code. You know that panic attack, WHY IS THIS THING NOT WORKING? and you do something like this:

int a;

// line 2001 this happens
use (a);

// 10000 lines of code

// line 10001
a = 0
use(a);

Oh damn my use(a) function is not working and than spend hour or two debugging perfectly working code. Some compilers would give you warning about this but some would not.

It is kind of like seat belt in a car, it is not likely that you will get into an accident but you put it on anyway, and you should not wait until you see a cop to put it on, because of that little chance that you can get in accident before you get to the cop.


If it’s obvious that the variable is never read before being initialised and the variable is always initialised (in every code path) before being read then yeah, that’s fine. In all other cases, you should initialise your variables.

Tags:

C