I am new to C and I am writing pseudo code here:
void fn(a) {}
fn(b)
It is correct to assume that in the function body fn what happens is this assignment
`a = b`
I know we can pass the reference/pointer instead of just the value. I get it. But at its core, it still does this assignment of parameter = argument right?
I would like to know:
- if there is any official term for this?
- when exactly does this assignment happen and what exactly makes this happen? is it the compiler?
CodePudding user response:
if there is any official term for this?
The official semantics of a function call are discussed in the “Function call” section of the C standard. There is no term specifically for the assignments of values to parameters.
C 2017 draft N4659 8.2.2 “Function call” [expr.call] 4 says:
When a function is called, each parameter (11.3.5) shall be initialized (11.6, 15.8, 15.1) with its corresponding argument…
when exactly does this assignment happen and what exactly makes this happen? is it the compiler?
It happens when a function is called. The compiler is responsible for generating code that produces a program that performs the semantics of the source code (as defined by the C standard).
CodePudding user response:
The C standard describes an execution environment, the results of various types of statements and the results of various types of expressions. A compiler is only required to produce code that, when,run, produces results as-if it were run on that described execution environment.
In terms of your actual question, that means that a function call in source code does not necessarily translate into any sort of call or jump instruction when run on actual hardware.
For example, given the function:
int sqr(int x, inty)
{
return x*y;
}
a compiler might well simply compute such a result in-place and not perform any sort of parameter passing. But whether you can actually count on that behavior is a detail left up to the compiler implementor.
All that being said, on actual hardware and without inlining, a function call's parameters are very much like any other variable initialization (think copy rather than assign). The exact details (such as order of parameter evaluation) are left up to each implementation.
