C++ Single line If-Else within Loop - c++

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.

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;

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

What is this "for" syntax called? [duplicate]

I have seen some very weird for loops when reading other people's code. I have been trying to search for a full syntax explanation for the for loop in C but it is very hard because the word "for" appears in unrelated sentences making the search almost impossible to Google effectively.
This question came to my mind after reading this thread which made me curious again.
The for here:
for(p=0;p+=(a&1)*b,a!=1;a>>=1,b<<=1);
In the middle condition there is a comma separating the two pieces of code, what does this comma do? The comma on the right side I understand as it makes both a>>=1 and b<<=1.
But within a loop exit condition, what happens? Does it exit when p==0, when a==1 or when both happen?
It would be great if anyone could help me understand this and maybe point me in the direction of a full for loop syntax description.
The comma is not exclusive of for loops; it is the comma operator.
x = (a, b);
will do first a, then b, then set x to the value of b.
The for syntax is:
for (init; condition; increment)
...
Which is somewhat (ignoring continue and break for now) equivalent to:
init;
while (condition) {
...
increment;
}
So your for loop example is (again ignoring continue and break) equivalent to
p=0;
while (p+=(a&1)*b,a!=1) {
...
a>>=1,b<<=1;
}
Which acts as if it were (again ignoring continue and break):
p=0;
while (true) {
p+=(a&1)*b;
if (a == 1) break;
...
a>>=1;
b<<=1;
}
Two extra details of the for loop which were not in the simplified conversion to a while loop above:
If the condition is omitted, it is always true (resulting in an infinite loop unless a break, goto, or something else breaks the loop).
A continue acts as if it were a goto to a label just before the increment, unlike a continue in the while loop which would skip the increment.
Also, an important detail about the comma operator: it is a sequence point, like && and || (which is why I can split it in separate statements and keep its meaning intact).
Changes in C99
The C99 standard introduces a couple of nuances not mentioned earlier in this explanation (which is very good for C89/C90).
First, all loops are blocks in their own right. Effectively,
for (...) { ... }
is itself wrapped in a pair of braces
{
for (...) { ... }
}
The standard sayeth:
ISO/IEC 9899:1999 §6.8.5 Iteration statements
¶5 An iteration statement is a block whose scope is a strict subset of the scope of its
enclosing block. The loop body is also a block whose scope is a strict subset of the scope
of the iteration statement.
This is also described in the Rationale in terms of the extra set of braces.
Secondly, the init portion in C99 can be a (single) declaration, as in
for (int i = 0; i < sizeof(something); i++) { ... }
Now the 'block wrapped around the loop' comes into its own; it explains why the variable i cannot be accessed outside the loop. You can declare more than one variable, but they must all be of the same type:
for (int i = 0, j = sizeof(something); i < j; i++, j--) { ... }
The standard sayeth:
ISO/IEC 9899:1999 §6.8.5.3 The for statement
The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the controlling expression that is
evaluated before each execution of the loop body. The expression expression-3 is
evaluated as a void expression after each execution of the loop body. If clause-1 is a
declaration, the scope of any variables it declares is the remainder of the declaration and
the entire loop, including the other two expressions; it is reached in the order of execution
before the first evaluation of the controlling expression. If clause-1 is an expression, it is
evaluated as a void expression before the first evaluation of the controlling expression.133)
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a
nonzero constant.
133) Thus, clause-1 specifies initialization for the loop, possibly declaring one or more variables for use in
the loop; the controlling expression, expression-2, specifies an evaluation made before each iteration,
such that execution of the loop continues until the expression compares equal to 0; and expression-3
specifies an operation (such as incrementing) that is performed after each iteration.
The comma simply separates two expressions and is valid anywhere in C where a normal expression is allowed. These are executed in order from left to right. The value of the rightmost expression is the value of the overall expression.
for loops consist of three parts, any of which may also be empty; one (the first) is executed at the beginning, and one (the third) at the end of each iteration. These parts usually initialize and increment a counter, respectively; but they may do anything.
The second part is a test that is executed at the beginning of each execution. If the test yields false, the loop is aborted. That's all there is to it.
The C style for loop consists of three expressions:
for (initializer; condition; counter) statement_or_statement_block;
The initializer runs once, when the loop starts.
The condition is checked before each iteration. The loop runs as long it evaluates to true.
The counter runs once after each iteration.
Each of these parts can be an expression valid in the language you write the loop in. That means they can be used more creatively. Anything you want to do beforehand can go into the initializer, anything you want to do in between can go into the condition or the counter, up to the point where the loop has no body anymore.
To achieve that, the comma operator comes in very handy. It allows you to chain expressions together to form a single new expression. Most of the time it is used that way in a for loop, the other implications of the comma operator (e.g. value assignment considerations) play a minor role.
Even though you can do clever things by using syntax creatively - I would stay clear of it until I find a really good reason to do so. Playing code golf with for loops makes code harder to read and understand (and maintain).
The wikipedia has a nice article on the for loop as well.
Everything is optional in a for loop. We can initialize more than one variable, we can check for more than one condition, we can iterate more than one variable using the comma operator.
The following for loop will take you into an infinite loop. Be careful by checking the condition.
for(;;)
Konrad mentioned the key point that I'd like to repeat: The value of the rightmost expression is the value of the overall expression.
A Gnu compiler stated this warning when I put two tests in the "condition" section of the for loop
warning: left-hand operand of comma expression has no effect
What I really intended for the "condition" was two tests with an "&&" between. Per Konrad's statement, only the test on to the right of the comma would affect the condition.
the for loop is execution for particular time for(;;)
the syntex for for loop
for(;;)
OR
for (initializer; condition; counter)
e.g (rmv=1;rmv<=15;rmv++)
execution to 15 times in for block
1.first initializ the value because start the value
(e.g)rmv=1 or rmv=2
2.second statement is test the condition is true or false ,the condition true no.of time execution the for loop and the condition is false terminate for block,
e.g i=5;i<=10 the condition is true
i=10;i<10 the condition is false terminate for block,
3.third is increment or decrement
(e.g)rmv++ or ++rmv

Why is a for loop's condition optional, but a while loop's isn't? [duplicate]

This question already has answers here:
Why can the condition of a for-loop be left empty? [duplicate]
(2 answers)
No loop condition in for and while loop
(5 answers)
Closed 4 years ago.
Why is for(;;) treated as an infinite loop while while() gives an error as it requires an expression? Why don't for loops expect expressions, too?
It just… doesn't.
while could have been made to permit an empty condition (which would presumably be interpreted as true), but then it would be asymmetrical with if for which this would make less sense.
Ultimately, there is no compelling reason to permit an empty condition in while preamble as any code using this would not be self-documenting.
For symmetry with for, you could require for(; true; ) — except now this looks weird because the declaration and update clauses may now be empty whereas the condition can't. Okay, let's make those mandatory too. So, what do we put in those places for no-ops? for (int dummy = 0; true; (void)dummy)? Now it's getting silly.
They're different language features and there's no strong reason to make them work the same way in this regard at the expense of other considerations.
Disclaimer: this answer explains why the syntax is valid, not why it was designed that way.
According to the documentation (emphasis mine):
formal syntax:
attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement
So all that is required is the init-statement and a ;. And for the init-statement, it says:
an expression statement (which may be a null statement ";")
So as a result, if you leave away the optional things and put a ; for the init statement, all you get is ;;.
In C it's a bit different:
for ( init_clause ; cond_expression ; iteration_expression )
loop_statement
init_clause, cond_expression, and iteration_expression are all optional
That's the two ; and three optional clauses/expressions. If you omit all three, you get ;; again.
This is a language design question, so language designers should chime in.
My opinion: the optional features (specially shortcuts) of a language should
PREVENT MISTAKES.
So, while() is easily a mistake (you omitted the conditional, eg. 0 or 1), whereas
for(;;) is rarely a mistake (you have to consciously type the 2 ;).

C++ for loop with no conditions

I ran across this
for ( ; ; ) {}
A quick cursory search lead me nowhere in finding out what this means. It looks like another thread might be handling terminating this. Is this equivalent to 'while (TRUE) {}' ?
This is an infinite loop. Any of the three parts of a for loop (initialization, condition and increment) can be missing. Specifically, if the condition in a for loop is missing, it is treated as being true. So it is equivalent to while(1) { ... }.
Yes they are equivalent in functionalities.

Why can the condition of a for-loop be left empty? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
No loop condition in for and while loop
Why is the condition in a for-loop allowed to be left empty? For example
for (;;)
compiles fine. Why does this empty expression evaluate to true but the following
if () {}
while () {}
will both fail? I want to know if/why the for-loop is an exception to this case.
http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf
These are the iteration statements
while ( expression ) statement
do statement while ( expression ) ;
for ( expression [opt] ; expression [opt] ; expression [opt] ) statement
for ( declaration expression [opt] ; expression [opt] ) statement
The while loop was designed to evaluate the controlling expression before each execution of the loop and the do loop was designed to evaluate after each execution.
The for loop was designed as a more sophisticated iteration statement.
6.8.5.3 The for statement
The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The
expression expression-2 is the controlling expression that is
evaluated before each execution of the loop body. The expression
expression-3 is evaluated as a void expression after each execution of
the loop body. If clause-1 is a declaration, the scope of any
identifiers it declares is the remainder of the declaration and the
entire loop, including the other two expressions; it is reached in the
order of execution before the first evaluation of the controlling
expression. If clause-1 is an expression, it is evaluated as a void
expression before the first evaluation of the controlling expression.
Both clause-1 and expression-3 can be omitted. An omitted
expression-2 is replaced by a nonzero constant.
The specification allows expression-2, the condition of the loop, to be omitted and is replaced by a nonzero constant. This means that the for loop will continue to execute indefinitely.
This is useful for allowing a simple syntax for iterating with no end.
for(int i = 0;;i++) { //do stuff with i }
That's much simpler to write and understand than writing a while(1) loop with a variable declared outside the loop and then incremented inside the loop.
The for loop specification then goes on to allow you to omit clause-1 so that you can declare or initialize variables elsewhere, and you can omit expression-3 so that you are not required to evaluate any expression upon completion of each loop.
The for loop is a special case. The while loop and the do loop are strict and require an expression, but the for loop is a flexible iteration statement.
I can't give a definitive answer, but my guess would be that it's because in the for loop case, there are three different expressions, each of which you may or may not need to use depending on the loop.
In the if case, it would make no sense if there were no expression; it would need to always act as if the expression were true or false, and thus be equivalent to just one of the clauses alone. In the while case, there would be a meaningful interpretation of while () { }, which would be to evaluate to while (1) { } (giving you a loop that you can break out of with break), but I guess that the benefits of leaving out that single character are not worth the trouble.
However, in the for loop case, there are three different expressions, each of which may or may not be needed. For instance, if you want to initialize and increment something on every loop, but will use break to break out of the loop, you can write for (i = 0; ; ++i), or if you just want the test and increment, because your variable is already initialized, you could write for (; i > 0; --i). Given that each of these expressions may not be necessary depending on your loop, making you fill in a placeholder for all that you do not use seems a bit cumbersome; and for consistency, rather than requiring a placeholder in one of them, all of them are optional, and the condition is considered to be a constant non-zero value if omitted.
Of course, it is sometimes easy to read too much intent into a design decision. Sometimes, the reason for a given standard is simply that that's how it was implemented in the first implementation, and everyone else just copied that. For an example, see Rob Pike's explanation of why files starting with . are hidden in Unix; it wasn't due to a deliberate design decision, but simply because someone took a shortcut when writing ls and didn't want to display the . and .. directory entries every time.

use of "else if" in c++

I have two questions -
(I)
code-fragment-1
if(<condition-statement>){
}
else if(<condition-statement-2>){
//statements-1
}
//statements-2
code-fragment-2
if(<condition-statement>){
}
else{
if(<condition-statement-2>){
//statements-1
}
//statements-2
}
Are the above two code fragments same?
(II) when are else ifs (in C++) used?
The only difference is in example 1 your Statement2 will get executed regardless of the conditions you check. In example 2, Statement2 will only get executed if your if condition is false. Other than that, they're basically the same.
No, in the first case you execute the else block only if the <condition-statement> is not verified AND only if <condition-statement-2> is verified.
In the second case you execute the else block simply if the <codition-statement> is not verified.
In this case are equivalent until you does not have any //statements-2.
About the question : when is the else if (in c++) used ?
Is used basically under the same conditions of all other languages​​ that have this construct.
else is executed as alternative to the related if, else-if is executed as alternative but with an 'attached' if to be verified, otherwise is not executed.
So they are not logically equivalent.
the syntax of an if is really
if(condition) statement;
What the {} really do is allow you to group together multiple statements. In your second example you only have one statement(the if) inside your {}s, so yes, both examples are the same, except //statements-2 always gets run when !=true
In your first code sample, statement-2 is executed unconditionally. In the second it is conditional. Not the same.
'else if' is generally to be preferred, because you can keep inserting or appending more of them indefinitely, or append an 'else', whereas with the other form you have to endlessly mess around with braces to get the same effect, and you risk altering the semantics, as indeed you have done in your second sample.