+ 2

Output of C++ code

Can anyone explain the output of this C++ code? #include <iostream> using namespace std; void fun(int* i, int* j) { *i = *i**i; cout << *i << endl; *j = *j**j; cout << *i << " " << *j << endl; } int main() { int i=2, j=3; fun(&i,&i); printf("%d, %d",i,j); return 0; } https://code.sololearn.com/c1ta1BwEW8kK/#cpp

27th Jul 2020, 9:29 PM
Edward Finkelstein
Edward Finkelstein - avatar
2 ответов
+ 6
fun(&I, &I) passing I refference so changes in function in i variable location reflect back in original value.. In function: *i stores *i; *j stores *i both stores same value i.e 2 *i = *i * *i now *i =4. Original actual argument value in main function also changes, and j also changes since j contains *i location and now *j also 4. Hence *j = *j * *j =4*4 =16. Now *i, *j both 16. And actual argument of main i also 16. Notice that j in main, not passed its values and not modified anywhere. So I, j in main prints 16,3 Point to be remembered &I address passing and in function works like *i (farmal) = &i (actual value).. For not to confuse, use different variable names... Hope it helps.......
27th Jul 2020, 10:03 PM
Jayakrishna 🇮🇳
+ 2
Thank you, I get it now.
27th Jul 2020, 10:13 PM
Edward Finkelstein
Edward Finkelstein - avatar