6.1. ARGUMENTS PASSING METHODS (CALLING CONVENTIONS)
6.1.7 Modifying arguments.
Sometimes, C/C++ programmers (not limited to thesePLs, though), may ask, what can happen if they
modify the arguments?
The answer is simple: the arguments are stored in the stack, that is where the modification takes place.
The calling functions is not using them after thecallee’s exit (the author of these lines has never seen any
such case in his practice).
#include <stdio.h>
void f(int a, int b)
{
a=a+b;
printf ("%d\n", a);
};
Listing 6.9: MSVC 2012
_a$ = 8 ; size = 4
_b$ = 12 ; size = 4
_f PROC
push ebp
mov ebp, esp
mov eax, DWORD PTR _a$[ebp]
add eax, DWORD PTR _b$[ebp]
mov DWORD PTR _a$[ebp], eax
mov ecx, DWORD PTR _a$[ebp]
push ecx
push OFFSET $SG2938 ; '%d', 0aH
call _printf
add esp, 8
pop ebp
ret 0
_f ENDP
Soyes,onecanmodifytheargumentseasily. Ofcourse,ifitisnotreferencesinC++(3.18.3onpage558),
and if you don’t modify data to which a pointer points to, then the effect will not propagate outside the
current function.
Theoretically, after thecallee’s return, thecallercould get the modified argument and use it somehow.
Maybe if it is written directly in assembly language.
For example, code like this will be generated by usual C/C++ compiler:
push 456 ; will be b
push 123 ; will be a
call f ; f() modifies its first argument
add esp, 2*4
We can rewrite this code like:
push 456 ; will be b
push 123 ; will be a
call f ; f() modifies its first argument
pop eax
add esp, 4
; EAX=1st argument of f() modified in f()
Hard to imagine, why anyone would need this, but this is possible in practice. Nevertheless, the C/C++
languages standards don’t offer any way to do so.
6.1.8 Taking a pointer to function argument.
...even more than that, it’s possible to take a pointer to the function’s argument and pass it to another
function: