Creating a basic calculator

Write your question here.
Hi, I am self teaching myself C++ (I have some prior experience) and going through the basics. When typing in a basic calculator, I have a question regarding these two statements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 (Statement 1)
#include <iostream>
using namespace std;

int main()
{
    int a;
    int b;
    int sum;

    cout << "Enter a number for a \n";
    cin >> a;

    cout << "Enter another number for b \n";
    cin >> b;

    sum=a+b;
    cout << "The sum of a and b is: " << sum;

    return 0;
}



[/code] (Statement 2)

#include <iostream>
using namespace std;

int main()
{
int a;
int b;
int sum;
sum=a+b;

cout << "Enter a number for a \n";
cin >> a;

cout << "Enter another number for b \n";
cin >> b;

cout << "The sum of a and b is: " << sum;

return 0;
}
[/code]

For Statement 1, when I enter 4 for both a and b, it calculates it correctly as 8.

But for Statement 2, when I enter 4 for both a and b, it calculates it as 6040903 (or something like that). Why is that Statement 1 is able to give the right solution?
1
2
3
4
int a;
int b;
int sum;
sum=a+b;


sum = null + null

Whereas in 1 is changed after a and b have been given values.
sum = null + null

Not quite.

In that example all the variable are un-initialised so they have garbage values. Garbage in, garbage out.

So the golden rule is to always initialise all variables to something. Zero is not necessarily always a good value, but often is.

The following is a little contrived:

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; // eventually learn to avoid this, Google why it is bad :+)

int main()
{
    int a = 0;
    int b = 0 ;
    int sum = -9999; // hopefully this won't clash with an actual correct answer

    cout << "Enter a number for a \n";
    cin >> a;

    cout << "Enter another number for b \n";
    cin >> b;

    //sum=a+b; // <--- intentional mistake here, commented out the whole line
    cout << "The sum of a and b is: " << sum; // still gives a identifiable but wrong answer

    return 0;
}
Topic archived. No new replies allowed.