C++ 循环中的单行 If-Else

C++ Single line If-Else within Loop

我阅读了 Why I don't need brackets for loop and if statement,但我没有足够的声誉点数来回答后续问题。

我知道这是不好的做法,但我一直面临着尽量减少我使用的代码行数的挑战。

你能在任何版本的 C++ 中做到这一点吗?

a_loop()
    if ( condition ) statement else statement

即if/else 块算作一个“语句”吗?

同样,if/else if.../else 算作一个“语句”吗?虽然这样做会变得完全不可读。

我上面提到的post,只说了这样的话:

a_loop()
    if(condition_1) statement_a; // is allowed.

是的,在语法上你可以这样做。

if/else块是一个selection-statement,这是一种语句。

N3337 6.4 选择语句说:

selection-statement:
    if ( condition ) statement
    if ( condition ) statement else statement
    switch ( condition ) statement

您可以使用 ternary operator 而不是 if...else

while(true) return condition_1 ? a : b;

while 如果它的参数值总是 true 在这里似乎是多余的,所以你可以简单地写

return condition_1 ? a : b;