0

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.
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Sanjit Raman
  • 53
  • 1
  • 1
  • 10
  • 1
    Did you simply try out yourself? – πάντα ῥεῖ Apr 02 '22 at 11:42
  • yup. It worked. It's worth keeping up in case someone else finds this relevant. – Sanjit Raman Apr 02 '22 at 11:48
  • 5
    ***I read this, but I don't have enough [SO] rank points to reply with a follow-up question*** You are never supposed to add a follow-up question to some other question. Instead you are supposed to add your own question and link to the previous question if needed. – drescherjm Apr 02 '22 at 11:50
  • I am aware of this. The actual code was a longer expression, but for simplicity, I wrote this. Question modified to most general form. – Sanjit Raman Apr 02 '22 at 11:52
  • @SanjitRaman just to add some more seemingly weird: https://stackoverflow.com/questions/514118/how-does-duffs-device-work – πάντα ῥεῖ Apr 02 '22 at 11:52
  • @drescherjm that is what I did right? Is this the correct way to do it? – Sanjit Raman Apr 02 '22 at 11:53
  • 1
    Yes what you did by asking a new question is correct. – drescherjm Apr 02 '22 at 11:54
  • I deleted my comment about reducing to 2 lines because the answer from @ShivCK is better. It's morning here and I obviously need more coffee.. – drescherjm Apr 02 '22 at 11:56
  • 1
    c++ syntax generally doesn't care about whitespace or newlines at all. Preprocessor directives and includes would be an exception, a few more might exist. But you should be able to write a whole program with classes and all on just one line if you want. – super Apr 02 '22 at 12:55
  • Yes I am aware, thank you. Our guidelines are vague, but just wanted to know whether I could make this simplification. – Sanjit Raman Apr 02 '22 at 16:24

2 Answers2

5

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;
ShivCK
  • 557
  • 10
  • 16
2

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
MikeCAT
  • 73,922
  • 11
  • 45
  • 70