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

ε祈祈猫儿з 提交于 2019-11-26 14:52:40

问题


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?


回答1:


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!




回答2:


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.



来源:https://stackoverflow.com/questions/28642693/why-cant-i-use-a-break-statement-inside-a-ternary-conditional-statement-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!