Reputation: 6772
Every time I initialize a variable within an if-statement's blocks and its else's blocks, and use it afterward, the compiler spits an error: the variable isn't declared. For example:
if (/*Some expression*/)
int a=5;
else
int& a=c;
//...
a++; // Variable not declared
My compiler would say that a is not declared. The main problem about any declaration other than in an if-statement is that in one case the variable a must be a reference, which must be set when it is initialized. Also, I don't really want to create a new variable unless it is necessary, which it isn't when it could be a reference.
Is there something else I'm doing wrong? Or a way to pass the error? Or some type of variable prototype?
Upvotes: 1
Views: 850
Reputation: 272637
Variables in C++ have a specific type; a
cannot be an int
sometimes, and an int &
at other times. So there is no way that your code would ever make sense. And as you've already found, the "scope" of variables is limited to the block they were declared in.
Without knowing what you're trying to solve, I can't really be any more specific than that.
Upvotes: 8