About the return value

Hi everyone! i am a totally newb in computer programming.

I had tried to run the c++ code below. After i run it, it showed that the y is 5 after the 1st time the function is called but y is 7 after the 2nd time the function is called.


Would someone explain why "y" is different in the first and second time please!? and also........what is the "return x;" at the end actually does!?
(Please explain in a very simple way because i really don`t know anything about c++)



Thanks a lot!!

-------------------------------------------------------------------------

#include<iostream> //for cin & cout out
#include<cmath>
using namespace std;

int add_two( int x ); // Adds 2 to its argument and returns the result

main() { // <--------------------------- int main( void )

int y = 5;

cout << "Before calling any function, y = " << y << endl;

add_two( y );

cout << "After calling the function once, y = " << y << endl;

y = add_two( y );

cout << "After calling the function twice, y = " << y << endl;

system("pause");

return 0;

} // main

int add_two( int x ) { // <--------------------- int add_two( int )

cout << "In function, x changed from " << x;

x += 2;

cout << " to " << x << endl;

return x;

} // add_two
1 When you use code use the code format ([code ][/ code])

2 read this before defining a function http://www.cplusplus.com/doc/tutorial/functions/

3 [code]main() { // <--------------------------- int main( void )[/code]
should be int main(){
1
2
3
4
5
cout << "Before calling any function, y = " << y << endl;

add_two( y );

cout << "After calling the function once, y = " << y << endl;

You should use a reference as parameter: http://www.cplusplus.com/doc/tutorial/functions2/
y starts as 5.

Then you do y = add_two(y).

Inside the add_two( int x ) function, x takes the value 5 that you passed it.
then x += 2 adds 2 to the value of x and x results in 7.

return x returns 7 as the result of the function add_two, therefore y = add_two(y) is the equivalent in this case of saying y = add_two(5) or y = 7.

hope this helps

Olivier

Topic archived. No new replies allowed.