Little help please!

Hello!

I have just started to learn the c++ language two days ago, and I seem to be stuck
on a simple (for some of you) problem.

Here is the code of the program that adds two int values together, and then shows the result:

#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;

int main(){
int a, b,;

int result;
result = a + b;


cout <<" Declare the value of the first number :";
cin >> a;

cout <<"Declare the value of the second number:";
cin >> b;



cout <<"Result of the operation is:" << result;

system("pause");
return 0;
}

My problem is with the declaration and the use of the "result" variable. In this given example the program checks out fine by the compiler but the value I get when executed is not true ( for example 5+5 = 10) but instead all I get is something( not 10 in the case shown before). My question is next:
if i move the declaration of the "result" variable after the outputs and inputs of the "a" and "b" variables the program works fine. So, why doesn't it work with the code shown above since i believe that ( in my c++ understanding so far ) it doesn't matter WHEN i declared the variable in the code since i haven't assigned any other value by the end of the code.
I hope someone can explain why is the result incorrect if "result" is declared before the variables that "result" is consisted of.
I'm sorry for the maybe wrong technical terms i've used in this question, since i'm in the c++ language for 48hrs now.
Thanks :)

I'm not sure if this is your typo, but you had an extra comma here at the end:
int a, b,;

Also, to resolve your problem, yes, it would help if you put result = a + b; after the two inputs, this is because the program works in order from top to bottom.

EDIT: Typo
Last edited on
ok a little thing here..
"int a, b,;"
get rid of that last comma:
"int a, b;"

the problem is you've assigned a value to result before the user has input values for a and b.
"int result;" is declared just fine, but this line:
"result = a + b;"
needs to be moved to after "cin >> b;"
then the value assigned to result will reflect the users input for a and b.
You must learn to distinguish between C++ "=" and common "equals to". If you put result = a + b; in the begining of the code, it does not mean result will be "equal to x plus y" for the duration of the program, even if x or y change. It will only have its value set as x+y, and it will never update by itself, except if you put another result = (whatever) statement later.
Last edited on
Thanx! Sorry about the comma, the compiler doesn't seem to have a problem with it.
Topic archived. No new replies allowed.