C++, Variable Declaration in 'If' Expression

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;

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++, variable declaration in 'if' expression

As of C++17 what you were trying to do is finally possible:

if (int a = Func1(), b = Func2(); a && b)
{
// Do stuff with a and b.
}

Note the use of ; of instead of , to separate the declaration and the actual condition.

How does one declare a variable inside an if () statement?

If you want specific scope for value, you can introduce a scope block.

#include <iostream>

int get_value() {
return 101;
}

int main() {
{
int value = get_value();
if(value > 100)
std::cout << "Hey!";
} //value out of scope
}

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

Initializing a variable inside of an if-statement in C?

The visibility of the variable count is just within the if() block

if()
{
//count is visible within if
}

// count is unknown here

Since count is not known outside of the if() block compiler is reporting error this can be fixed by moving the variable declaration outside of the if() block like

int count;

if()
{
// count is visible
}
// count is visible

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


Related Topics



Leave a reply



Submit