Variable not initialized

when i try to run this program i get a messege saing that the variable A has not been initialised. (its a stupid program i know, but i whant to understand why it doesnt work)

#include <iostream>
using namespace std;
int main()
{
unsigned int A, B, C = (A*A+B*B);
cout << "enter value for side a " << endl;
cin >> A;
cout << "enter value for side b"<< endl;
cin >> B;
cout << C;
cin >> A;

cin.ignore();
return 0;
}
Last edited on
C++ isn't declarative. The order of operation matters.
1
2
3
4
5
6
7
8
unsigned int A, B;
cout << "enter value for side a " << endl;
cin >> A;
cout << "enter value for side b"<< endl;
cin >> B;
unsigned int C = (A*A+B*B);
cout << C;
cin >> A;
When you define a variable like int A; that variable contains a random value that you can not and MUST not use. To make it usable you have to initialize it, which means assigning a defined value to it. The plain old way is doing int A = 0; but in C++ you can also do int A(0);.
Like Helios pointed out, you are initializing 'C' with a combination of the values of 'A' and 'B' which are uninitialized, therefore you can't use them.
Last edited on
Multiple assignments is right associative. I assume you are familiar with order of operations from mathematics ( BOMDAS or PEMDAS depending on where you live). This means that....



unsigned int A, B, C = (A*A+B*B);
is equivalent to...
1
2
unsigned int A, B, C;
C = (A*A+B*B);


As everyone else has said, variables must be defined (initialized) before usage. C++ is right associative, which means that when you declare multiple variables on one line, an assignment only assigns the value to the right-most variable, in this case, C. However, since A and B are undefined at that point, the compiler complains.
C++ is right associative, which means that when you declare multiple variables on one line, an assignment only assigns the value to the right-most variable, in this case, C.
Well, this is just false on several accounts.
First of all, C++ is neither left- nor right-associative. Some operators associate to the left and others associate to the right. Most associate to the left, though.
Second, it's not true that only the right-most variable gets assigned. What if you do unsigned int A, B=0, C;?
Yes, if you only put an assignment at the end of a list of variables in a declaration, only the last one will be assigned, but this has nothing to do with order of operations because the declaration as a whole is not an expression. The above declaration doesn't get parsed like this:
unsigned int (A, B, C) = (A*A+B*B);
It gets parsed like this:
unsigned int (A), (B), (C = (A*A+B*B));
Topic archived. No new replies allowed.