Addition in function

closed account (S1q43TCk)
I know how to fix that code, but why for input 0 output is 32765?

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

using namespace std;

void Addition(int a, int b) {
  cout <<a+b<< "\n";
}

int main() {
    int x,y;
    cout<<"Give numbers to add them:";
    cin>>x,y;
  Addition(x,y);

  return 0;
}
Last edited on
Careful with your streamed input. In C++ the comma operator (,) means something rather different to what it might in this context in other languages. You should have
cin >> x >> y;


why for input 0 output is 32765?

y hasn't been initialised, so output is undefined. (It isn't 32765 in cpp.sh).
If you write
cin>>x,y;
then it is equivalent to successive statements
1
2
    cin>>x;
    y;

The latter is a "do-nothing" statement.
Last edited on
Hello PeterL,

To start with "x" and "y" are defined and left uninitialized. There is no way of knowing what value they have.

Next is line 12. The use of the comma operator does not work the way you are thinking.

So when you call the function you are sending a new value for "x' thet you could enter and an unknown garbage value for "y".

This is your code with some blank lines, space and some additions that tend to make the output better
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

void Addition(int a, int b)
{
  cout << "\n The answer is: " << a + b << "\n";
}

int main()
{
    int x{}, y{};  // <--- Always a good idea to initial your variables.
    
    cout<<"Give numbers to add them ( 1 2): ";
    
    cin >> x >> y;
    
    //std::cout << x << "  " << y << '\n';  // <--- Used for testing.
    
    Addition(x, y);

  return 0;
}

Notice how the blank lines make it easier to read. Also some spaces help the code. Last is the use of "\n"s to break up the output. No one likes reading something where everything is run together.

To the compiler blank lines and white space are ignored. To the reader it makes a big difference.

Andy
Topic archived. No new replies allowed.