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

  • A+

I know that using an uninitialized variable is wrong, but the question arises in the context of an uninitialized integer, that I do not use before I assign it a value later on in the code.

Should I expect to get weird results? Or is it just bad practice?

I am a freshman computer science student, sorry for any mistakes!


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 a = someArray[i];//it is not known what value 'i' is. Fault if > 9.  

Where someArray is defined as:

int someArray[10]; 

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. 


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