简体   繁体   中英

Why is the function return in C a statement?

An expression generates a value, statements alter the status of the machine, aka, side effects. However, I keep reading that function return is a statement. If I call a function that returns a void, how does that change any status of the machine? Or if I call a function that returns a non-void value, if I don't use it but just calling it how this changes any status?

I just don't get why the return is a statement?

Source: Concepts in Programming Languages. Cambridge: Cambridge University Press, 3.4.1 Statements and Expressions, p. 26

It changes the call stack and program counter. It puts the return value in a known place (depending on calling conventions)

Even if you don't use the return value, the compiler still needs to store it somewhere as it may be called from different compiler units that are unknown.

statements alter the status of the machine

Except when they don't. There are statements in C that have no side effects.

A statement is also a syntactic construct - it's not about whether it has side effects or not, it's about where it fits in the language grammar.

When a program is running, the CPU needs to keep track of where it is in the code. This is done using a 'register' that is called, variously, a program counter , an instruction pointer , an address register or any one of a number of other, similar names.

The value in this, just like that in any other register or memory location, constitutes part of the "status of the machine." Furthermore, it is probably the most important 'status' with regards to running a program.

When your program executes a return statement, the value in this 'address register' is changed - to a value that corresponds to the piece of code immediately following the call to the function from which your are returning.

The return statement also (almost always) changes a number of other registers that comprise the status of the machine; for example, the stack pointer (if used) will be reset to its value before the call to the function was made.


Note: I have grossly oversimplified the CPU-level, run-time mechanics involved in calling (and returning from) a function here; however, the 'example' will hopefully illustrate the point that the return statement must affect the "status of the machine!"

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