Programming Fundamentals · Interview question

Why should you always initialize a variable when you declare it?

A strong answer

A declared-but-not-initialized local variable contains whatever bits happened to be in that stack slot before the function ran, leftover from a previous function call, garbage from an interrupt handler, anything. Reading it is undefined behavior. The symptom is a bug that appears intermittently and changes when you adjust unrelated code (because the unrelated code changes the stack layout). Initializing at declaration eliminates an entire class of "works on my machine" bugs. Modern compilers will warn about this with -Wall or -Wuninitialized.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Variables & Data Types

Named boxes that hold a value. Pick a type, declare, assign, and learn why C makes you say what kind of thing each box holds.

More Variables & Data Types questions

Browse all 472 interview questions