+ 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; }
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.
+ 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)â