Defining a variable in the condition part of an if-statement?
This is allowed by the specification, since C++98.
From Section 6.4 "Selection statements":
A name introduced by a declaration in a condition (either introduced by the type-specifier-seq or the declarator of the condition) is in scope from its point of declaration until the end of the substatements controlled by the condition.
The following example is from the same section:
if (int x = f()) {
int x; // ill-formed, redeclaration of x
}
else {
int x; // ill-formed, redeclaration of x
}
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!
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
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.
- 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
}
- 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()) {
Defining a variable in the condition part of an if-statement does not allow comparison of its value. Why?
So, why I can't check the value of the newly defined variable in the same place?
Because the syntax doesn't allow it. The condition can be either a declaration or an expression. An expression can't declare a named variable, and a declaration can't be used as an expression.
how is the condition of the first if evaluated?
The variable is initialised, and its value converted to bool
. The condition succeeds if that yields true
.
But is it guaranteed by the standard?
Yes:
C++11 6.4/3 The value of a condition that is an initialized declaration in a statement other than a
switch
statement is the value of the declared variable contextually converted tobool
.
Why can't we define a variable inside an if statement?
This is because section 8.5.1 of the C# language spec. states:
Furthermore, a variable initializer in a local variable declaration corresponds exactly to an assignment statement that is inserted immediately after the declaration.
This basically means that, when you do:
StringBuilder sb = new StringBuilder("test")
You're, in effect, doing the exact same thing as:
StringBuilder sb; sb = new StringBuilder("test")
As such, there is no longer a return value for your check against != null
, as the assignment isn't a single expression, but rather a statement, which is a local-variable-declarator comprised of an identifier followed by an expression.
The language specification gives this example, stating that this:
void F() {
int x = 1, y, z = x * 2;
}
Is exactly equivalent to:
void F() {
int x; x = 1;
int y;
int z; z = x * 2;
}
Declare variable in if statement (ANSI C)
No, you cannot do that.
What you can do is create a compound statement (anonymous or hanging block) just for the if
{
int variable;
variable = some_function();
if (variable) return 1;
}
/* variable is out of scope here */
Note that for this simple case you can call the function as the condition of the if
(no need for an extra variable)
if (some_function()) return 1;
Why can't variables be declared in an if statement?
Why? There can be no code path leading to the program assigning 1 to b without declaring it first.
You are right, but the compiler doesn't know that. The compiler does not execute the code. The compiler only translates to bytecode without evaluating expressions.
Related Topics
How to Find the Intersection of Two Stl Sets
Use Std::Fill to Populate Vector with Increasing Numbers
How to Clear the Console in Both Windows and Linux Using C++
How to Run Application Which Requires Admin Rights from One That Doesn't Have Them
Obtain a Std::Ostream Either from Std::Cout or Std::Ofstream(File)
How to Correctly Use Cv::Triangulatepoints()
Questions About Hinnant's Stack Allocator
Return Type Covariance with Smart Pointers
Differencebetween a MACro and a Const in C++
Why Doesn't Emplace_Back() Use Uniform Initialization
Why Does C++11 Have 'Make_Shared' But Not 'Make_Unique'
How to Pause a Pthread Any Time I Want
Atomicity in C++:Myth or Reality
Differentiate Between Function Overloading and Function Overriding
Do I Need to Protect Read Access to an Stl Container in a Multithreading Environment