Search code examples
c++loopsconditional-statementsbraces

C++ Single line If-Else within Loop


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.

Solution

  • 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