Home > Net >  What if declared variable in condition of if statement is not convertible to bool
What if declared variable in condition of if statement is not convertible to bool

Time:09-05

The reference says in the syntax of if statement that:

attr(optional) if constexpr(optional) ( init-statement(optional) condition ) statement-true
...
condition - one of

  • expression which is contextually convertible to bool
  • declaration of a single non-array variable with a brace-or-equals initializer.

But for the second choice, the variable is not requested to be contextually convertible to bool

So I tried

struct Foo { int val; };
int foo() {
    if (Foo x{}) { return 1; }
    return 0;
}

and I got an error with both gcc and clang.

Clang said that error: value of type 'Foo' is not contextually convertible to 'bool' and gcc gave a similar message error: could not convert 'x' from 'Foo' to 'bool'.

So my question is, is it just omitted as a consensus, or I missed something? Thanks ;)


Update: Thanks for @Sneftel! I've found in https://eel.is/c draft/stmt.pre#5:

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 to bool.

CodePudding user response:

So my question is, is it just omitted as a consensus, or I missed something?

From stmt.pre#4:

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 to bool.

(emphasis mine)

This means that in the second case, the value of the declared variable must be contextually converted to bool which is not the case in your example and hence the error.

This in turn means that the quoted statement from cppreference in your question should add this "contextual conversion to bool" in their 2nd case.

  •  Tags:  
  • c
  • Related