Passing by Value | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Passing by Value

So, Sololearn uses this code as an example for passing by value in c++: void myFunc(int x) { x = 100; } int main() { int var = 20; myFunc(var); cout << var; } // Outputs 20 My first question is: For what reason is the 100 there, if we dont use it at all? And my second question is: Is there anyway of calling the 'x' with cout. Because when I try to output the x and the var at once in the main function, it tells me that x was not declared, even though we declare it at the start. Because if not, the x at the start kinda feels useless in that case.

22nd Mar 2019, 5:50 PM
tobiasth2003
tobiasth2003 - avatar
2 Answers
+ 3
1st question: sometimes you want to change var to check something but you don't want to change it in main, just in that function = pass by value 2nd question: x is only visible in myfunc so cout it inside that function, when you return from myfunc to main, program doesn't remember x anymore
22nd Mar 2019, 5:54 PM
Elva
Elva - avatar
+ 1
Thanks for the quick answer
22nd Mar 2019, 5:56 PM
tobiasth2003
tobiasth2003 - avatar