Interview Questions

People told me that if I evaluated an undefined expression

C Interview Questions and Answers


(Continued from previous question...)

People told me that if I evaluated an undefined expression

Q: People told me that if I evaluated an undefined expression, or accessed an uninitialized variable, I'd get a random, garbage value. But I tried it, and got zero. What's up with that?

A: It's hard to answer this question, because it's hard to see what the citation of the ``unexpected'' value of 0 is supposed to prove. C does guarantee that certain values will be initialized to 0 , but for the rest (and certainly for the results of those undefined expressions), it is true that you might get garbage. The fact that you happened to get 0 one time does not mean you were wrong to have expected garbage, nor does it mean that you can depend on this happening next time (much less that you should write code which depends on it!).

Most memory blocks newly delivered by the operating system, and most as-yet-untouched stack frames, do tend to be zeroed, so the first time you access them, they may happen to contain 0, but after a program has run for a while, these regularities rapidly disappear. (And programs which unwittingly depend on a circumstantial initial value of an uninitialized variable can be very difficult to debug, because the ``expected'' values may coincidentally arise in all the small, easy test cases, while the unexpeccted values and the attendant crashes happen only in the larger, longer-running, much-harder-to-trace-through invocations.)

(Continued on next question...)

Other Interview Questions