+ 3

Why does my simple calculator always answer as 8?

I just started learning a few hours ago, so bear with me. I wrote it as follows #include <iostream> using namespace std; int main () { int a; int b; int c = a+b; cin >> a; cin >> b; cout << c; return 0; } No matter what I input or don't input into the variables when it asks, it always answers "8". I'm very confused.

18th Apr 2018, 10:18 PM
Kirby
6 RĂ©ponses
+ 6
Hi Kirby, a couple of simple rules. When initializing a variable, try always to give it a value. If you don’t, the variable will get the value of the (unprepared) memory address. That’s why you have weird random numbers. So, first of all, initialize: int a = 0; int b = 0; Then, the sum “int c = a+b;” MUST come after that a and b has received their values, otherwise you’re using variables that still must have their value assigned. // correct order cin >> a; cin >> b; int c = a+b;
18th Apr 2018, 10:26 PM
Luigi
Luigi - avatar
+ 4
When you declare a variable, the cpu assigns to that single variable a space grabbed from the free memory. For an int type, it’s generally 4 bytes. If you don’t give it a value, the compiler will assign it a “default” value (to make debug easier), other times it won’t. So what you’re reading is a totally strange value, such as 8. If you assign a value on the declaration, you eliminate this weird behaviour. int a = 0; prepares all the 4 bytes belonging to the variable a to be 0. That’s it :)
18th Apr 2018, 10:41 PM
Luigi
Luigi - avatar
+ 4
Before your program runs there is some code wrapped around your code that sets things up. That code left behind values in the memory a and b was assigned and those values added together happened to be 8. If you changed the order you defined things by slipping a 'int d;' in between a and b, you would get a different answer.
19th Apr 2018, 12:40 AM
John Wells
John Wells - avatar
+ 3
all i know for now is that you cannot add the variables before they're assigned a value in this case write c = a+b after cin >> a cin >> b not before
18th Apr 2018, 10:25 PM
Mind To Machine đŸ’»đŸ•†
Mind To Machine đŸ’»đŸ•† - avatar
+ 3
Thank you! That solved the problem easily. I would still like to know where it kept getting "8" from though, since "8" was nowhere in the code. lol
18th Apr 2018, 10:27 PM
Kirby
29th Apr 2018, 3:18 PM
Programmer Gaurav
Programmer Gaurav - avatar