Marco Merlini
Marco Merlini

Reputation: 965

C++ pass by reference: how is the call stack used?

A curiosity that's been nagging at me:

Consider this function:

void add10(int& x) {
    x += 10;
}

I've been programming in C for a long time, so I know exactly what it means to do this:

void add10(int *x) {
    (*x)+=10;
}

The address of x is pushed on the stack (along with the return address, dynamic link, etc.), and the function itself dereferences it.

But how is the call stack used in the first case? Is it simply a syntactic shortcut for the second case?

Upvotes: 2

Views: 640

Answers (2)

gsamaras
gsamaras

Reputation: 73444

Is it simply a syntactic shortcut for the second case?

That is implementation defined.

Usually yes, since the reference is internally implemented as a pointer.


PS: Your claims about how 2nd case works, are far from accurate. You need to re-approach it.

Upvotes: 0

Aganju
Aganju

Reputation: 6405

There is no generic answer, as it depends on the compiler - it can do whatever it wants, as long as the result is correct.
Typically, it would be treated the same way as a pointer. Also, typically, it would be inlined, so nothing ever goes on the stack (but again, it depends on the compiler and the context)

Upvotes: 2

Related Questions