Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Single line If-Else within Loop

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading