Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading