+ 1

Its output is 5. WHY?

#include<iostream> using name std void sum(int &a) { a=5; } int main() { int a=9; sum(a); cout<<a; return 0; }

29th Aug 2019, 12:03 PM
Opeeyum
Opeeyum - avatar
3 Answers
+ 2
Function sum() not returning any value. But, it is taking address of 'a' as argument. So, change made in sum() is visible outside the function. See 'call by the reference' for more information.
29th Aug 2019, 2:53 PM
Kuri
Kuri - avatar
+ 2
You have a function that takes “a”, which is initialised as “9”, as a parameter. You also pass it to that function by reference, which means that the “a” from the “main” function will be changed as well if you perform any changes to the “a” inside the “sum” function. You changed “a” to equal 5 inside the “sum” function, so when “a” returns in main, it still equals 5. If you don’t want that, then don’t pass “a” by reference. Correct this; “void sum(int &a)” with this; “void sum(int a)”
31st Aug 2019, 7:40 AM
Kireii
Kireii - avatar