noob. help!!!

so im following a online tutorial and making a simple c++ program. but i came across something that confused me. when i assign the value of "sum" at the start, the compiler gives me some crazy number, but when i assign the value a bit further down it gives me the right answer. for example
#include <iostream>

using namespace std;

int main()
{
int a;
int b;
int sum= a+b;
cin>>a;
cin>>b;
cout<<sum;
return 0;
}

the above program gives me a ridiculous answer which is -7.......but when i do this.
#include <iostream>

using namespace std;

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

cin>>a;
cin>>b;
sum = a +b;
cout<<sum;
return 0;
}

it gives me the right value. So my question is why cant i assign the value of "sum" at the start?
closed account (3CXz8vqX)
Hehe, programming in C is procedural. If you tell it to do something it'll try to do it, even though it might not know exactly what to do.

In your first version you have asked it to put the sum of a and b into 'sum'. Yet you haven't told it what a and b are yet. If you assign a and b before asking it to add them together, then it knows what to add together instead of picking numbers out of the air.

It's like me asking you "Recite that book you learned earlier". Even though you haven't yet learned a book. C++ is stupid enough that it'll attempt it anyway!


Try this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

int main()
{
int a;
int b;

cin>>a;
cin>>b;

int sum= a+b;

cout<<sum;
return 0;
}
thank you for the quick reply and the simple explanation
Topic archived. No new replies allowed.