Why is taking address of function argument allowed in C?

Viewed 89

Suppose I write two functions:

int f() {
    return 1;
}

int g() {
    int* x = &f();
}

I can't compile this in C, because you "cannot take the address of an rvalue". That makes sense, because the return value from f lives in a register. (That is to say, it doesn't have an address to assign.)

On the other hand, I can compile this:

int h(int x) {
    int* y = &x;
    return 0;
}

Why? The argument to h also lives in a register, so it should not have an address. What am I misunderstanding?

1 Answers

Function parameters are objects with automatic storage duration just like local variables inside of the function.

Section 6.9.1p8 of the C standard says the following regarding function parameters:

Each parameter has automatic storage duration; its identifier is an lvalue. The layout of the storage for parameters is unspecified.

And because function parameters are lvalues, their address can be taken.

Also, although not explicitly stated by the C standard, function parameters often reside on the stack just like local variables.

Related