C++ Local Variable [duplicate]

one of my students asks the question that what is the life of local variable in c++. i told him that it is limited to the body of that function in which it was used

This is inaccurate. The lifetime of an automatic variable extends until at the end of the scope where the variable is declared. For example, a variable in a compound statement (also known as block) extends until the end of that compound statement whether that compound statement is the body of the function, or nested within a function body.


void foo() {
       int i;
    // lifetime of i has ended, but function hasn't returned yet

Each scope has different rules for how far they extend. For example, the scope of function arguments extend until the end of the function. The scope of names declared in sub-statements of a control structure (like a loop or a conditional statement) extend until the end of the control structure.

Static local variables have static storage duration and their lifetime is not bound by the scope of their declaration.

i declared two functions fun() and fun2() and declare int i in both functions. according to my concept both int i of fun() and fun2() will be saved as different variables in memory but both function gives me same memory location

They are “saved as different variables”, but that has nothing to do whether the variables will be stored in a separate memory location.

In fact, according to your concept, the lifetime of the local variable of fun has ended, so there is no reason why the local variable of fun2 couldn’t use the same memory where the – now destroyed – object used to be.

Browse More Popular Posts

Leave a Comment