how come the following code doesn't print out that i want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

int function(int x, int y);


int main()
{
    int x, y;
    function(x,y);
    return 0;
}

int function(int x, int y)
{
    cin>>x;
    cin>>y;
    return (x+y);
}


after i input two values and the program ends, it doesn't return me the sum of the 2 values.
@Yangfizz

For one, x and y have no values. Your not passing anything to function(int, int y). Below is probably not the best way of doing it, but this works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
    int x, y, sum;
   cin>>x;
    cin>>y;
    sum = function(x,y);
    cout << sum << "\n"; 
}

int function(int x, int y)
{
 
    return (x+y);
}
i know what you saying, so the any value after return will not be printed out on the screen?
Well, your original code didn't do anything with the value returned from the function.

Your code:
1
2
    function(x,y);
    return 0;


needed at least something like this:
1
2
    cout << function(x,y);
    return 0;


Or you could have:
1
2
3
    int sum = function(x,y);
    cout << "Sum = " << sum;
    return 0;


Basically, the reason nothing was printed was because there was no cout in the code shared in the opening post above.

Topic archived. No new replies allowed.