3 ms·
Those first two suggestions are good. The last one, not so good. First, it's not very random. As you point out, it will often just be zero. If zero is acceptab
by mikeash 12y ago
Those first two suggestions are good. The last one, not so good.
First, it's not very random. As you point out, it will often just be zero. If zero is acceptable to you, then just initialize it to zero. If you need something reliably different then you can't count on uninitialized memory to deliver it.
Second, it will trip diagnostics in tools like Valgrind, which you'll have to either silence or ignore.
Third, and this is a real fun one, any C program which reads from uninitialized memory is non-conforming, which means that the compiler is allowed to assume that it never happens. For an example, let's say you wrote some code to flip a coin "randomly":
int uninitialized;
if((uninitialized % 2) == 0) printf("heads");
else printf("tails");
The compiler would be within its rights to eliminate both branches of the if statement. It would, in fact, be within its rights to start a game of nethack upon encountering such code (as early versions of gcc did when encountering a #pragma statement) or make demons fly out of your nose (a common example of what C compilers are allowed to do with such things, albeit one that's somewhat difficult to implement).
Don't read uninitialized variables. It's the law!