Possible Duplicate:
Scope of variables in if statements
Say i have the following code;
int y = 5;
if (.... ) {
int x = 10;
x = y;
}
Is there a way i can use the variable x outside of the if scope?
Possible Duplicate:
Scope of variables in if statements
Say i have the following code;
int y = 5;
if (.... ) {
int x = 10;
x = y;
}
Is there a way i can use the variable x outside of the if scope?
No. The scope of x
is within the if
. Declare x
outside of the if
if you want to use it elsewhere. If you try to reference x
in the line following that if
you will get a compilation error.
Apart from putting x
outside the if
block, no. A variable can only be used within its scope.
This is what the C++ standard has to say about it in basic.scope.declarative
:
Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity. In general, each particular name is valid only within some possibly discontiguous portion of program text called its scope.
As a consequence, using it elsewhere is invalid.