I need to place two dependent init statements within one if
condition. As a raw example:
if (bool x = false; bool y = true) std::cout << "Check!\n";
The whole expression evaluates to true, and that is the problem. Suppose I want to test a pointer in the first statement and dereference this pointer to test something else in the second statement:
if (auto ptr = ptr_to_check; auto sth_else = ptr_to_check->sth_else()) { /* do something */ }
And this one is going to crash as I can still dereference nullptr
. I want to avoid nested if's as in my program there are other statements nested within this one. Can I place these two statements within one condition somehow?
CodePudding user response:
When it comes to several statements within one if
, only the last statement is evaluated as a condition. In this case, a ternary operator is a solution:
if (bool x = false; bool y = x ? true : false) std::cout << "Check!\n";
So, in case of pointers:
if (auto ptr = ptr_to_check; auto sth_else = ptr_to_check ? ptr_to_check->sth_else() : sth_evaluating_to_false) { /* do something */ }