6

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!

  • 4
    Not a problem. Just don't try to use it before initializing it. – lurker Feb 18 '19 at 12:16
  • 3
    C is very lenient with uninitialized variables. It says that the value or contents of an uninitialized automatic (i.e. local) variable is *indeterminate*. Reading its value is actually okay as long as that value doesn't represent a *trap-value*, because then it's *undefined behavior*. It is however very bad practice to use the values or contents of uninitialized automatic variables. – Some programmer dude Feb 18 '19 at 12:19
  • your question indicates you probably defined your variable too early – bruno Feb 18 '19 at 12:23
  • 1
    On the other hand, taking the address of an uninitialized automatic variable is perfectly fine in all situations. It's common to pass pointers to the variables to functions, where the function do the initialization of the variable. Most common example: Passing a pointer to the first element of an uninitialized array to a function, like for example the first argument for `strcpy`. – Some programmer dude Feb 18 '19 at 12:23
  • 2
    You declared (defined), you assigned (write) , you used (read) - you're OK. – Sourav Ghosh Feb 18 '19 at 12:30
  • 3
    @Someprogrammerdude: Reading the value of an uninitialized automatic object is not “actually okay.” Per 6.3.2.1 2, accessing an uninitialized object of automatic storage duration whose address has not been taken has behavior not defined by the C standard. According to the standard, It may trap or behave in any manner, not just give an indeterminate value. – Eric Postpischil Feb 18 '19 at 12:42
  • @EricPostpischil I had a similar discussion a couple of years ago, but then had the opposite position and was told that I was wrong then. Now it seems I'm still wrong. Ah well, live and learn. :) – Some programmer dude Feb 18 '19 at 12:45
  • "I assign it a value" is just another way to say that you initialized it. That it didn't happen in the exact same place where you declared the variable does not matter. – Hans Passant Feb 18 '19 at 12:54
  • Thank you all! A question to @bruno - am I not supposed to declare all variables at the start of a function, say I am writing in ANSI C89? I have been getting errors from my compiler, saying c:79:15: warning: ISO C90 forbids mixing declarations and code [-Wdeclaration-after-statement] – BendixDeveloper Feb 18 '19 at 13:04
  • 1
    @BendixDeveloper oh you have an old version, in that case create sub blocks {}, the closer a definition is to its uses, the better it is – bruno Feb 18 '19 at 13:07
  • Possible duplicate of [(Why) is using an uninitialized variable undefined behavior?](https://stackoverflow.com/questions/11962457/why-is-using-an-uninitialized-variable-undefined-behavior) –  Feb 18 '19 at 16:45

4 Answers4

7

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.
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
ryyker
  • 22,849
  • 3
  • 43
  • 87
3

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.

1

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.

Indiana Kernick
  • 5,041
  • 2
  • 20
  • 50
-1

Nothing bad will happen for now if you have unitialized variables, and don't try to read a meaningful value from them (you are allowed to read them, nothing bad will happen either, but their content is garbage).
But it's a good practice to initialize as many of your variables as possible, as even if your code may be fine for now, if you change it later you may introduce much harder to find bugs if you left some variables not initialized.
Especially when there are lots of different possible execution paths, as with multiple threads / processes / interrupts...

B. Go
  • 1,436
  • 4
  • 15
  • 22
  • *you are allowed to read them, nothing bad will happen either* -- not true. It is [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior) to read an uninitialized variable if it never had its address taken. It is also UB if the indeterminate value contained in the variable is a trap representation. – dbush Feb 18 '19 at 13:43
  • I understand that reading from an uninitialized pointer could be really bad, as that could go anywhere, including from a null value (an error), but I don't see (as much) the risk with a local variable (place reserved in stack) or a global variable (in the data memory), especially an integer (no non coding values being possible, on contrary to floats where some impossible to get (32 bit hexa) value exist). Now I just had to go read about trap violations... expecially as I didn't use C99 yet. And maybe I always got lucky / used good compilers so far! – B. Go Feb 20 '19 at 00:01
  • 1
    https://stackoverflow.com/questions/11962457/why-is-using-an-uninitialized-variable-undefined-behavior?noredirect=1&lq=1 => Ok, I get it! Especially from the post with registers... – B. Go Feb 20 '19 at 00:20