What's the Scope of a Variable Initialized in an If Statement

What's the scope of a variable initialized in an if statement?

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.

(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)

Why is variable declared in an if-statement still in scope in else block?

Why is variable declared in an if-statement still in scope in else block?

Because the standard says that it is. It was designed so presumably because it is useful.

  1. How is this possible?

It's unclear why it wouldn't be possible.

I always thought that scope of such variables ends with the if-block.

You assumed wrongly.

I'd be thankful for quotation from the standard if possible. [language-lawyer]

Latest draft says:

[stmt.select.general]

Selection statements choose one of several flows of control.
selection-statement:

  • ...
  • if constexpropt ( init-statementopt condition ) statement else statement
  • ...

Note that the entire if (condition) statement else statement is a selection-statement.

[basic.scope.block]

Each

  • selection or iteration statement ([stmt.select], [stmt.iter]),
  • ...

introduces a block scope that includes that statement or handler.

Note that the condition is directly within the if-statement and not inside a sub-statement, and thus a declaration within it extends until the end of the entire block scope, which contains both the if-sub-statement, and the else-sub-statement (not standard names for those sub-statements).

There is also a pretty clear example that demonstrates ill-formed re-declarations, and incidentally shows the scope of such declaration:

if (int x = f()) {
int x; // error: redeclaration of x
}
else {
int x; // error: redeclaration of x
}



  1. If it's legal though, shouldn't it at least generate a warning?

Yeah, it would be nice if compilers were able to detect all provable null pointer indirections at compile time. It may be worth submitting a feature request regarding this corner case.

Are there any reasonable applications of such feature?

Sure. Following fabricated example seems reasonable to me:

if (Response r = do_request()) {
log << "great success. content: " << r.content;
} else {
log << "someone broke it :( error: " << r.error_code;
}

Or if you dislike implicit conversions:

if (Response r = do_request(); r.is_success()) {

Scope of variables in if statements

"Do variables declared in a conditional go out of scope at the end of the conditional?"

Yes - the scope of a local variable only falls within enclosing brackets:

{
int x; //scope begins

//...
}//scope ends
//x is not available here

In your case, say you have class A.

If you're not dealing with pointers:

A a( condition ? 1 : 2 );

or if you're using a different constructor prototype:

A a = condition ? A(1) : A(2,3);

If you're creating the instance on the heap:

A* instance = NULL;
if ( condition )
{
instance = new A(1);
}
else
{
instance = new A(2);
}

or you could use the ternary operator:

//if condition is true, call A(1), otherwise A(2)
A* instance = new A( condition ? 1 : 2 );

EDIT:

Yes you could:

A* x = NULL; //pointer to abstract class - it works
if ( condition )
x = new B();
else
x = new C();

EDIT:

It seems what you're looking for is the factory pattern (look it up):

 class A; //abstract
class B : public A;
class C : public A;

class AFactory
{
public:
A* create(int x)
{
if ( x == 0 )
return new B;
if ( x == 1 )
return new C;
return NULL;
}
};

javascript variable scope in the IF statement

1) Variables are visible for the whole function scope. Therefore, you should only declare them once.

2) You should not declare the variable twice in your example. I'd recommend declaring the variable at the top of the function, then just setting the value later:

function actionPane(state) {
var structure;
if(state === "ed") {
structure = {
...

For excellent feedback on JavaScript, I highly recommend using JSLint by Douglas Crockford. It will scan your code for common errors, and find suggestions for cleanup.

I also recommend reading the small book JavaScript: The Good Parts. It contains a lot of tips for writing maintainable JS code.

Python life variables in if statement

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module. However Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.

Taking into consideration your example:

if 2 < 3:
a = 3
else:
b = 1
print(a)

Note that a isn't declared or initialized before the condition unlike C or Java, In other words, Python does not have block-level scopes. You can get more information about it here

Python variable scope in if-statements

if statements don't define a scope in Python.

Neither do loops, with statements, try / except, etc.

Only modules, functions and classes define scopes.

See Python Scopes and Namespaces in the Python Tutorial.

c++ weird scope in if statement

Redeclaring a variable in an inner scope creates a new variable.

#include <iostream>

int main()
{
int i = 1;

if (true)
{
int i = 42; // variable is re-declared
} // lifetime of inner i ends here

std::cout << i; // expected output 1

}

You can reference a variable in an inner scope that was declared outside without re-declaring it.

#include <iostream>

int main()
{
int i = 1;

if (true)
{
i = 42; // variable from outer scope is used
}

std::cout << i; // expected output 42

}

C++ If-statement variable scope

The problem is that you are shadowing the outer variable numer with an inner variable of the same name.

See: Shadowing variables

You can assign to the variable numer from the inner scopes, instead of declaring new variables.

double calc_real_root(double a, double b, double c, double disc, double operation)
{
double denom=2*a;
double numer;
if (operation == ADD)
{
// Assign to `numer` without declaring new variable.
numer = -b + sqrt(disc);
}
else
{
numer = -b - sqrt(disc);
}
return numer / denom ;
}

Initializing variables in an if statement

It limits the scope of length to the if alone. So you get the same benefits we originally got when we were allowed to write

for(int i = 0; i < ... ; ++i) {
// ...
}

Instead of the variable leaking

int i;
for(i = 0; i < ... ; ++i) {
// ...
}

Short lived variables are better for several reasons. But to name a couple:

  1. The shorter something lives, the less things you need to keep in mind when reading unrelated lines of code. If i doesn't exist outside the loop or if statement, then we don't need to mind its value outside of them. Nor do we need to worry its value will interact with other parts of the program that are outside of its intended scope (which may happen if i above is reused in another loop). It makes code easier to follow and reason about.

  2. If the variable holds a resource, then that resource is now held for the shortest period possible. And this is without extraneous curly braces. It's also made clear the resource is related to the if alone. Consider this as a motivating example

    if(std::lock_guard _(mtx); guarded_thing.is_ready()) {
    }

If your colleagues aren't aware of the feature, teach them! Appeasing programmers who don't wish to learn is a poor excuse to avoid features.

Declaring Variable in an If Statement (Java)

The problem you encounter is that you have declared the variable within the if statement, meaning it may only be accessed within the { }. This article goes over the basics of variable scope in Java. You will only be able to access a variable from a scope if the variable was defined in a scope that is a subset of the current scope.

To achieve what you want, you will need to declare the variable outside the if-statement so that it can be accessible. Note you will need to handle the case when month is invalid otherwise you will have the default value of 0.

int month = 0;
if (in.hasNextInt()) {
month = in.nextInt();

if (!(month > 0 && month <= 12)) {
month = 0;
System.out.println("ERROR");
}
} else {
// Handle graceful exit
}

...
if (0 < month && month <= 3) { ... }


Related Topics



Leave a reply



Submit