New course! Every coder should learn Generative AI!
Try a free lesson0
why is the output 904 404?
#include <iostream> void doSmth(int &a, int &b, int c) { a = b + c; b = 0; c = 3; } int main(){ int x = 3; int y = 5; int z = 4; doSmth(x, y, z); std::cout << x << y << z << "\n"; doSmth(x, y, z); std::cout << x << y << z << "\n"; while (true); return 0; }
3 Answers
+ 1
The doSmth function declaration accepts 1st & 2nd argument (a and b respectively) as reference (read/write access), but the 3rd argument (c) is accepted as copy (read-only access), this means, changes to 'c' argument inside doSmth will not reflect on valuef 'z' in main procedure.
* In main procedure
x = 3, y = 4, z = 5
* Entering doSmth function
doSmth(3, 4, 5)
a = b + c (4 + 5) => 9
b = 0 => 0
c = 3 (doesn't affect z in main, z remains 4)
* Back in main procedure
print x, y, z => 9, 0, 4
* Entering doSmth function
doSmth(9, 0, 4)
a = b + c (0 + 4) => 4
b = 0 => 0
c = 3 (doesn't affect z in main, z remains 4)
print x, y, z => 4, 0, 4
Hth, cmiiw
+ 1
when the function is called firstly a(i.e. x) is set to 9, and b(i.e. y) to 0..... I hope you know calling a function by reference .... c=3; is useless because c is a local variable of the function and is destroyed as soon as function ends....
hence now values of x, y, z are 9, 0, and 4(unchanged) respectively...
next time the function is called a(i.e. x) is set to b(i.e. y i.e. 0 ) + c(i.e. 4) hence a(i.e. x) is equal to 4 now......
b(i.e. y) is again set to 0 and value of z is still unaltered....
hence finally the values are 4 , 0 , 4
+ 1
aaaahhhh, thank you both, i understant now💪