Node is a very simple class with a just a constructor and a few variables: a "name" (actually just a char) and two child Node pointers called "left" and "right".
I was just starting to write some code that needs to drop to the left-most node, and I was quite pleased when I came up with this:
Node *current = this->root;
while (true) (current->left != nullptr) ? current = current->left : break;
Seems simple enough: in an infinite loop, check to see if current has a left child, if so, set current to that left child, if not, break out of the loop. It's a cool little one-liner, not too unreadable. (And I commented it!)
Well, my compiler doesn't like it:
iterator.cpp:20:70: error: expected expression
while (true) (current->left != nullptr) ? current = current->left : break;
^
1 error generated.
Also, just throwing some braces into the while loop and moving the ternary operator to it's own line didn't help (unsurprisingly). I had to turn it into an if/else for the compiler to accept it.
Can someone explain how it's interpreting the one-liner and why it objects?
The ternary conditional operator is an operator that combines multiple expressions into a larger expression. break
is a statement and not an expression, so it can't be used inside a ternary conditional expression.
You could, though, rewrite your code like this:
while (current->left != nullptr) current = current->left;
Hope this helps!
Why can't I use a “break” statement inside a ternary conditional statement in C++?
Because the ternary operator isn't a statement at all, it's an operator, and it is composed of expressions, not statements. break
is a statement, not an expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With