Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the function return in C a statement?

Tags:

c

statements

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

like image 369
SLN Avatar asked Sep 19 '20 23:09

SLN


3 Answers

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.

like image 154
Lou Franco Avatar answered Oct 23 '22 20:10

Lou Franco


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.

like image 30
John Bode Avatar answered Oct 23 '22 20:10

John Bode


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!"

like image 5
Adrian Mole Avatar answered Oct 23 '22 19:10

Adrian Mole