Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use a "break" statement inside a ternary conditional statement in C++?

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?

like image 507
King Spook Avatar asked Feb 21 '15 06:02

King Spook


2 Answers

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!

like image 200
templatetypedef Avatar answered Nov 14 '22 23:11

templatetypedef


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.

like image 45
user207421 Avatar answered Nov 14 '22 22:11

user207421