+ 1

C++ Address-of Operator &

[1] char f1(char c) { return c == 'z' ? 'a' : c + 1; } char f2(char &c) { c = f1(c); return c; } int main() { char x = 'x'; cout << f2(x); cout << f2(x); cout << f2(x); } Output: yza f1 function changes the value of its argument as well as f2 function. Do we pass the x variable itself to f2 above or do we pass its address? I thought we should pass the address if we want our variable to change its value. What is the difference between these two functions' declarations? [2] Imagine we have a similar function with such a declaration: char f3(char *c); that changes its arguments' value as well. What would be the result of these actions: a) char x = 'x'; cout << f3(x); b) char x = 'x'; cout << f3(&x); ? How should I interpret receiving variables/pointers/addresses as arguments by functions? Thanks in advance.

28th Jul 2018, 6:56 PM
Steppenwolf
Steppenwolf - avatar
1 Respuesta
+ 4
Emitted Assembly code in debugging mode on VSC++ (without involving cout object for the sake of simplicity) char x = 'x'; mov byte ptr [x], 78h // Load the memory address indicated by label x to 78h (120 or 'x') f2(x); lea eax, [x] // Place the effective addres of x (pointer to mem location indicated by x) into accumulator register push eax // Push the addres of x into program stack. call f2 (11B2550h) // obvious enough, calling the f2(by address of x) Live version for GCC: https://godbolt.org/g/Rdeeks In case of f3(char *), calling as f3(x) is a compilation error. The legal form would be as char f3(char *c) { *c = f1(*c); return *c; } int main() { char x = 'x'; char *xp = &x; // method 1 f3(&x); // method 2 f3(xp); } Pointer and reference are pretty much identical in what they do. The big advantage of having a reference parameter is to passing large objects or containers witch otherwise cause deep copying and lead to performance penalty.
28th Jul 2018, 7:39 PM
Babak
Babak - avatar