Programming Fundamentals · Interview question

What's the difference between local, global, and static variables?

A strong answer

A local variable is declared inside a function or block; it's created when control enters the block and destroyed when it leaves, and it's visible only inside that block. A global variable is declared outside any function; it lives for the entire program run and is visible from its declaration to the end of the translation unit (and across translation units if declared extern). A static local, static int x; inside a function, is like a global in lifetime (lives for the whole program, retains its value between calls) but local in visibility (only the enclosing function can see it). The general guidance: prefer locals because their lifetime and visibility are smallest; reach for static locals when a function needs persistent state between calls; reach for globals only when truly shared state is needed and isolation is impossible.

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

Functions

Naming a chunk of logic so you can call it from many places. Parameters in, return value out, scope rules: the building block of every program.

More Functions questions

Browse all 472 interview questions
What's the difference between local, global, and static variables? | EmbeddedPrep.io