C++ Single line If-Else within Loop

16.8k Views Asked by At

I read Why I don't need brackets for loop and if statement, but I don't have enough reputation points to reply with a follow-up question.

I know it's bad practice, but I have been challenged to minimise the lines of code I use.

Can you do this in any version of C++?

a_loop()
    if ( condition ) statement else statement

i.e. does the if/else block count as one "statement"?

Similarly, does if/else if.../else count as one "statement"? Though doing so would become totally unreadable.

The post I mentioned above, only says things like:

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

There are 2 best solutions below

0
MikeCAT On BEST ANSWER

Yes, syntactically you can do that.

if/else block is a selection-statement, which is a kind of statement.

N3337 6.4 Selection statements says:

selection-statement:
    if ( condition ) statement
    if ( condition ) statement else statement
    switch ( condition ) statement
0
ShivCK On

You can use ternary operator instead of if...else

while(true) return condition_1 ? a : b;

while seems redundant here if the value of its argument is always true so you can simply write

return condition_1 ? a : b;