Scope of Variables in If Statements

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;
}
};

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()) {

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.

C - Variable Declaration in If Condition Available in Else?

You can't declare a variable like this

 if((int a = 0))

The compiler does not allow the code to run and you get an error

and if you try this

if(something_that_is_false){
int a = 12;
}
else{
do_something;
}

again error because they are on the same level and they do not have access to their local variables.

Warning: you can use this code and runs without error

int a;
if(a=0){
printf("True");
}
else{
printf("False");
}

and you will see 'False' in screen because It's like writing

if(0) // and its false!

and for the last

int a;
if(a=0){
printf("True");
}
else{
printf("False");
}

you will see 'True' in screen because It's like writing

if(5) // any number other than zero is true!

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 ;
}

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

How to access the variables after if-condition when the variable is defined inside the if-condition in python

Your problem appears to be the fact that you are referencing a variable outside of its scope. Essentially what is happening is in your if statement you are creating a variable exclusively for use within the if scope. Effectively when you have said print vn.firstChild.nodeValue you can also imagine it as being any other variable such as print undefinedVar. What is occuring is your are referencing (calling) upon the variable before it has even been defined.

However, no worries here since this is very easy to fix. What we can do is simply create your vn and test variables outside of the if scope, hence inside your actual method by doing the following:

vn = None
test = None

for DO in range(count) :
atnnames = doc.getElementsByTagName("atnId")[DO]
atn = atnnames.childNodes[0].nodeValue
if atn == line[0]:
vn = doc.getElementsByTagName("vn")[DO]
vncontent = vn.childNodes[0].nodeValue
y = vncontent.encode('utf-8')
# print y
if '-' in y:
slt = (int(y.split('-')[0][-1]) + 1)
test = y.replace(y.split('-')[0][-1], str(slt))
# print test
else:
slt = (int(y.split('.')[-1]) + 1)
test = y.replace(y.split('.')[-1], str(slt))
# print test
else:
#print test
vn.firstChild.nodeValue = test
print vn.firstChild.nodeValue

This basically just creates an empty variable in the outermost scope. I've set the values to None since they get defined once your for loop runs. So what happens now is you have a variable which has been declared outside, and is None at the start, but as you run your for loop you are not creating a temporary variable just inside the if statement, but you are actually changing the value of

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

}

Variable scope inside if statements

You can declare new1 before the if block and use make inside:

var new1 []string

if len(array1)>len(array2) {
new1 = make([]string, 0, len(array1))
// instructions ...
} else {
new1 = make([]string, 0, len(array2))
// other instructions ...
}

new2 := make([]string, 0, len(new1))
copy(new2, new1)


Related Topics



Leave a reply



Submit