Home > Software engineering >  C Single line If-Else within Loop
C Single line If-Else within Loop

Time:04-03

Why I don't need brackets for loop and if statement

I read this, but I don't have enough [SO] rank 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.

Thanks

CodePudding user response:

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;

CodePudding user response:

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
  • Related