简体   繁体   中英

Can a variable declared inside a function stays in the stack even after the function call gets over in C/C++?

Below is my code in C++. Here in the function "temp", 1st, the value of 'ch' is declared & then printed(at the first time 'ch' is not initialized so 'ch' has Undefined value).Then "if" condition is satisfied(Inside "if" no work is done). Then function gets over & returned to the next line of the function call(increments 'i'). Then the next iteration also goes in the same way as the previous call. The same cycle goes on until a key is pressed. When a key is pressed(for eg 'a' is pressed), "else" gets executed & the key pressed is taken by getch(). Then function gets over & returned to next line of function call(i++), then in all the coming next iteration, when a function is called, 'ch' is assigned with the previous key pressed('a') and it prints that character('a'). It goes on printing 'a' until another key is pressed. Why & how 'ch' is assigned with the previous function call's value. Is the value of variable of previous call is stored inside the stack & assign it to the next call's variable?

#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;

int flag = 0,i = 1;

void temp()
{
    char ch;
    cout<<ch;
    if(!_kbhit())
    {

    }
    else{
        ch=_getch();
    }
}

int main()
{
    while(flag!=1)
    {
        temp();
        i++;
    }
   return 0;
}

In your code (and on Intel), after calling temp() and it returned, there is no code that modifies the location of ch on the stack. As a consequence it still has the previous value when you call it again.

Would you call for example printf() in main() after calling temp() , then this call would overwrite the location of ch .

To answer your specific question, you are just getting lucky.

C++ doesn't clear out memory unnecessarily. When you call temp() for a second or subsequent time, in this case it it allocates memory in exactly the same way as the previous time, and so you see the same value in ch .

However, any slight change to you programme structure or to your compiler settings could mean that the memory layout was not aligned and you wouldn't get this behaviour.

As suggested in the comments, changing the declaration to

static char ch;

would guarantee that the value was preserved between calls, at a potential very slight cost to memory and performance.

"Why and how ch is assigned with the previous function call's value?"

"Is the value of the variable ch of the previous call stored inside the stack and assigned to ch in the next call to temp() ?"

In C++, function-local objects do not need to be destroyed after the function has returned, which seems to be in your case.

Nonetheless the behavior is undefined . What you trying to understand is based upon undefined results of your execution.

Since ch is not initialized, printing its value could output any value.

That it prints the character 'a' at all other function calls to temp() is a sign of undefined behavior.


You can find a well-defined solution for this by qualifying the variable ch with the static storage-class specifier which means the variable ch is stored in the BSS segement of your executable, Fe:

static char ch;

Then ch keeps alive in the stack memory even between function calls with its value.

This furthermore also has the beneficial side effect, that ch is automatically 0 initialized. Thus, no undefined behavior anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM