2

Will the compiler produce the same code for both of these statements?

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

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

Will it simply write a pointer into the parameter part of foo's stack frame? Or, in the second case, will the callers' and foos' stack frames somehow overlap such that the callers' local variable takes the same memory on the stack as the parameter for foo?

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Mat
  • 11,263
  • 10
  • 45
  • 48
  • Should be exactly same. Whenever in doubt about these cases, better to check the disassembly. – Andy Jan 08 '10 at 13:46

4 Answers4

4

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

Bohemian
  • 412,405
  • 93
  • 575
  • 722
Richard Pennington
  • 19,673
  • 4
  • 43
  • 72
2

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
  • 48,893
  • 5
  • 92
  • 171
0

regarding overlapping of stack frames I found the following info here :

For some purposes, the stack frame of a subroutine and that of its caller can be considered to overlap, the overlap consisting of the area where the parameters are passed from the caller to the callee. In some environments, the caller pushes each argument onto the stack, thus extending its stack frame, then invokes the callee. In other environments, the caller has a preallocated area at the top of its stack frame to hold the arguments it supplies to other subroutines it calls. This area is sometimes termed the outgoing arguments area or callout area. Under this approach, the size of the area is calculated by the compiler to be the largest needed by any called subroutine.

So in your case if only variables in local scopes of caller functions are passed to foo2 overlapping thing may be possible!

Pooria
  • 2,017
  • 1
  • 19
  • 37
0

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
  • 204,818
  • 23
  • 294
  • 489