views:

121

answers:

3

hi!

foo1(int* val){(*val)++;}

foo2(int &val){val++;}

will the compiler create in both cases the same code? will it simply write a pointer into the parameterpart of foo's stackframe? or will in the second case the callers' and foos' stackframes somehow overlap such that the callers' local variable takes the same memory on the stack as the parameter for foo?

+4  A: 

Those two calls should generate exactly the same code, unless you have some kind of wierd compiler.

Richard Pennington
A: 

The stacks cannot be made to overlap.

Consider that the argument could be a global, a heap object, or even if stored in the stack it could be not the very last element. Depending on the calling convention, other elements might be placed in between one stack frame and the parameters passed into the function (i.e. return address)...

And note that even if nothing was added in the stack, the decision cannot be made while compiling the function, but rather when the compiler is processing the calling function. Once the function is compiled, it will not change depending on where it is called from.

David Rodríguez - dribeas
A: 

It depends.

The code generated for both will be equivalent if not identical on most platforms if compiled to a library.

Any good compiler will inline such a small function, so it is quite possible that rather than getting the address of something on the stack incrementing the pointed-to value, it will instead increment the value directly. Any inlined function's stack frame is embedded in the caller's stack frame, so the will overlap in that case.

Pete Kirkham
so also the version that takes a pointer would be inlined and instead of working with a pointer, would work directly on the actual variable?
Mat
@Mat: The reference version can also be inlined.
Martin York