The if statement determines which branch to take based on the value of the condition. This value is contextually converted to a bool and evaluated[1].
[0] https://en.cppreference.com/w/cpp/utility/to_chars_result
The if statement determines which branch to take based on the value of the condition. This value is contextually converted to a bool and evaluated[1].
[0] https://en.cppreference.com/w/cpp/utility/to_chars_result
Your comment seems to imply the condition is evaluated before initialising the variable(s) at all; is that what you meant? If so, this beast would work (even though it's undefined behaviour to construct a std::string from nullptr, and std::string is not convertible to bool):
const char* foo() // may return nullptr
if (std::string s = foo())But I could be wrong, the paper for the feature is linked but I didn't read it (!).
Yes exactly, my example would work?
> My hunch is to remember that in `auto [to, ec] = std::to_chars(p, last, 42)` the two names `to` and `ec` are not "real" variables/objects, but ...
Oh so my example wouldn't work after all (because std::string s is a "real" variable/object)?
In case of structured binding
The decision variable of the declaration is the invented variable e introduced by the declaration.
but in your case its simply: The decision variable of the declaration is the declared variable.Thus, in your example, the bool check would apply to "s", after the expression is evaluated.
The fact that foo() may return nullptr at runtime and your "s" is UB is your fault for running with scissors.
so "this beast would work" for some definition of "work". But not because of order of evaluation.
Most modern C++ compilers would warn you about not using a bool in a conditional anyway.
This is a contradiction. There is no expression in my code that evaluates to s. foo() is an expression, and then std::string s = ... is assignment initialisation, which is not an expression.
Edit: I suppose that if I used another form of initialisation, the answer becomes a bit more obvious:
if (std::string s('x', 3))
(Not that this makes sense but just the point is to use a constructor with more than one argument.) In this case it's clear the test has to be the just-initialised variable. In fact there could be no arguments at all!x = y is an expression statement in C++, which can be evaluated in an "if" for its side-effects.