I am starting again with c++ and was thinking about the scope of variables. If I have a variable inside a function and then I return that variable will the variable not be "dead" when it's returned because the scope it was in has ended?
I have tried this with a function returning a string and it did work. Can anyone explain this? Or at least point me to some place that can explain this to me please.
Thanks
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.
Advertisements. A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed. There are three places where variables can be declared in C programming language − Inside a function or a block which is called local variables.
When a function has a return statement in other blocks, the compiler adds a new variable and returns that value before returning from that function.
Scope Of A Variable in C. Lifetime Of A Variable in C. Scope of a variable determines the area or a region of code where a variable is available to use. Lifetime of a variable is defined by the time for which a variable occupies some valid space in the system's memory. Scope determines the life of a variable.
When the function terminates, the following steps happen:
The function’s return value is copied into the placeholder that was put on the stack for this purpose.
Everything after the stack frame pointer is popped off. This destroys all local variables and arguments.
The return value is popped off the stack and is assigned as the value of the function. If the value of the function isn’t assigned to anything, no assignment takes place, and the value is lost.
The address of the next instruction to execute is popped off the stack, and the CPU resumes execution at that instruction.
The stack and the heap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With