Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope and return values in C++

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

like image 591
AntonioCS Avatar asked Nov 08 '08 21:11

AntonioCS


People also ask

What are return values in C?

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.

What are scopes in C?

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.

What is the scope of return statement?

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.

What is scope and lifetime in C?

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.


1 Answers

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

like image 168
Christian C. Salvadó Avatar answered Sep 27 '22 20:09

Christian C. Salvadó