In C/C++, what does the following mean?
for(;;){
...
}
It's an infinite loop, equivalent to while(true). When no termination condition is provided, the condition defaults to false (i.e., the loop will not terminate).
In C and C++ (and quite a few other languages as well), the for loop has three sections:
a pre-loop section, which executes before the loop starts;
an iteration condition section which, while true, will execute the body of the loop; and
a post-iteration section which is executed after each iteration of the loop body.
For example:
for (i = 1, accum = 0; i <= 10; i++)
accum += i;
will add up the numbers from 1 to 10 inclusive.
It's roughly equivalent to the following:
i = 1;
accum = 0;
while (i <= 10) {
accum += i;
i++;
}
However, nothing requires that the sections in a for statement actually contain anything and, if the iteration condition is missing, it's assumed to be true.
So the for(;;) loop basically just means:
don't do any loop setup;
loop forever (breaks, returns and so forth notwithstanding); and
don't do any post-iteration processing.
In other words, it's an infinite loop.
Loop until some break, exit, throw etc. statement inside the loop executes. Basically, you can think of a for loop as consisting of:
for (setup; test; advance)
...
If the "test" is empty it's considered to be true, and the loop keeps running. Empty "setup" and "advance" simply do nothing.
An infinite loop which continues until there is a break, exit, or goto statement.
Even if this answer suggests that both constructs are equivalent, there's a subtle difference between both for(;;) and while(1) (which both create infinite loops) in the C language (and possibly compiler-dependent).
Some compilers (Windriver DIABData for instance) complain about "condition is always true" when using while(1).
Changing to for(;;) allows to get rid of the warning, probably because the latter expression is semantically stronger to create an infinite loop on purpose, and there is no "always true" condition at all (plus it's shorter to write).
On the other hand, the C++ language doesn't make a difference about both constructs as Adrian stated in comments:
The C++ standard states that a missing condition makes the implied while clause equivalent to while(true) and for ( for-init-statement condition opt ; expression opt ) statement is equivalent to { for-init-statement while ( condition ) { statement expression ; } }
Related
i've this code here:
for(i = openGates[0]; i < closeGates[0]; i++) {
if(str[i] == '(') {
closeGates.removeFirst();
openGates.removeAt(1);
}
}
If brace found, closeGates[0]'s value will change. Will it change the number of iterations?
Yes, the iteration-expression is executed after every iteration of the loop.
Reference for this answer :
https://en.cppreference.com/w/cpp/language/for
Apparently, no one decided to answer and I want to close this question so: yes, in C++ 'for' loop evaluates its conditions before every iteration thus the number of the iterations might change.
I am doing a program for tic-tac-toe and i have a line with
for ( count = 1; count < 10 && winner == 0; count++ );
I referred to other programs and came up with this.
And I'm not very sure of what the entire line means. I have searched up online but I dont understand the meaning of initialization statement ( count = 1 ) and the test expression. And also want to clarify, count++ means increase count right?
Let's have a look at the structure of a for loop:
for ( init-statement; condition; iteration_expression) statement;
From cppreference, a for loop does the following:
Executes init-statement once, then executes statement and iteration_expression repeatedly, until the value of condition becomes false. The test takes place before each iteration.
For your case:
init statement: at the beginning count is initialized to 1
condition: check if count is less than 10 and you don't have a winner yet
iteration_expression: cout++ increases count by 1
statement: you haven't provided that, but it will be executed until the condition is false.
Syntax of for loop is
for(initialization; condition; increment/decrement){
statement;
}
initialization:
Before we start looping, we will initialize the variable to certain value.
In this case, you are initializing 'count' variable to 1
Condition:
In condition part, To stop the loop at certain point you have to provide some conditions.
In this case, condition is 'count<10 && winner==0'. Note that, you are using And(&&) operation so, loop will stop only after both of the conditions are satisfied.
increment/decrement:
Based on the problem, you can choose to increment or decrement the loop variable('count'). In this case, count++ means you are incrementing the count by 1 after each iteration.
for (initialize;condition;increment/decrement)
for loop means
you initialize the variable
you apply a condition to stop the for loop
you execute a single time the loop body (if the condition satisfied)
then you increase or decrease the value of that variable and go to step 2
When I compile and run the code below with either counter++ or ++counter substituted for x, the output is identical; in both cases, numbers 1 - 10:
for (int counter = 1; counter < 11; x)
{
std::cout << counter << endl;
}
Originally I thought ++counter would increment by 1 and then return the new value before for boolean expression in the loop header was evaluated. i.e when starting with counter = 1 and using ++counter, counter would have a value of 2 in the boolean expression. This appears to not be the case, as both outputs are identical rather than the ++counter version having one less iteration, like I expected.
Reading around, it appears ++counter and counter++ increment counter by 1 at either the start or end of the loop body respectively. In which case is this not, at least conceptually, an identical action? Because the end and the start of the loop are the same thing once the loop has past the first iteration.
The only time I can see this making a difference is in the first iteration, where std::cout << counter << endl;should output 1 to the console if counter++ is used (because 1 is added to counter at the end of the loop). Whilst std::cout << counter << endl; should output 2 to the console if ++counter is used (because 1 is added to counter at the start of the loop).
In addition to the question above, could you please precisely explain the order in which the three actions are evaluated in the for loop header, and explain exactly where the iterations occur when using i++ and ++i.
Many thanks!
There is no difference. In older compilers, ++counter was faster because it did not create a temporary variable but all modern compilers can optimize that out. For heavy objects with custom (non-inlined) increment operators, ++counter can still be more efficient.
As for when evaluation takes place:
for (initialization; condition; increment/decrement)
code;
is evaluated as
{
initialization;
while (condition)
{
code;
increment/decrement;
}
}
The C++ for-loop may be roughly considered as syntactic sugar for the following (using your example):
int counter = 1;
while (counter < 11)
{
std::cout << counter << endl;
x;
}
So, the initialization statement is executed first, the condition expression is executed before each iteration, and the increment statement is executed at the end of each iteration.
We can see here that using post-increment or pre-increment operators makes no difference to the loop logic, though there may be other differences (post-increment actually requires keeping a copy of the old value of the variable as that is the value of the expression, which has some associated costs, see Preincrement faster than postincrement in C++ - true? If yes, why is it?).
counter++ makes a copy increase counter and returns the value
++counter increases counter and returns counter.
In loop
for(initialization;condition;increment/decrement)
{body;}
increment/decrement is the last line of the loop. So it will start the loop again when increment/decrement returns a value. So post-increment or pre-increment will not affect here. See this
What is the difference between pre-increment and post-increment in the cycle (for/while)?
printf("What do you do?\n1. Walk Away.\n2. Jump.\n3. Open Door.\n\n");
scanf("%d",&Choice);
printf("\n\n\n");
while(4<=Choice,Choice<=0);
{
printf("That is not a choice.\n");
printf("What do you do?\n1. Walk Away.\n2. Jump.\n3. Open Door.\n\n");
scanf("%d",&Choice);
printf("\n\n\n");
}
So this is my program. It works but what I want it to do is to repeat until an answer of 1, 2, or 3 is put in. But no matter what the answer is it has it go through the while loop then continue regardless of the next choice. (Also, I did declare "Choice"; I just didn't want to show the whole program.)
There are two problems in your code. Your while-loop expression is incorrect. The comma does not do what you think it does: in C/C++, the comma executes the left-hand expression and evaluates to the right-hand expression, meaning that in your case you are only checking the second condition. You probably want:
while(4<=Choice || Choice<=0)
The || is the OR operator, which returns true if either of the expressions around it are true.
Secondarily, there is a misplaced semicolon at the end of the while loop:
while(4<=Choice,Choice<=0); //<-- this should not be here
This marks the end of the loop, meaning that your code is parsed as:
while(4<=Choice,Choice<=0); //loop body is empty
{
//and we have a random unnamed block following it
}
Remove the semicolon and your while loop should execute correctly.
C and C++ have a comma operator, which has the lowest precedence of all operators. It evaluates the left operand and throws the result away, and then evaluates the right operand. Thus, your while condition is equivalent to:
while (Choice <= 0)
You also have a bug because there is a semicolon immediately after the condition, which makes for an infinite loop if Choice is not strictly positive (because nothing in the loop changes the value of Choice).
What you probably intended to write was:
while (Choice >= 4 || Choice <= 0)
{
...
}
The comma operator , doesn't test both conditions, it simply returns the second of the two. So your while loop is the equivalent of:
while(Choice<=0) ;
and since there's a ; following the statement, it is in fact an infinite loop if the condition is met. Good thing you didn't enter a choice of -1.
for (; cnt--; dp += sz)
{
pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
}
Could some one explain how this for loop works? It belongs to a cpp file.
I dont understand the condition in the for loop and how it is being checked. (The function is being invoked)
The general form of for statement looks like this:
for (init-statement; condition; expression)
statement
init-statement is used to initialize or assign a starting value that is modified over the course of the loop. condition serves as the loop control. As long as condition evaluates as true, statement is executed. expression is evaluated for each iteration only if condition is true
Back to your code:
for (; cnt--; dp += sz)
init-statement here is a null statement that does nothing. condition is cnt-- which evaluates its value as cnt then decrements 1. If cnt is non-zero, condition is true, if cnt is zero, condition is false.
The condition is being interpreted as a true or false scenario.
If it's 0, then it will be false, else true.
This is equivalent to the following code -
for(; cnt-->0; dp += sz);
Because as long as a value is not equal to 0, it is considered to be true.
Remember that normal integers can be used as boolean values as well, where zero is false and everything non-zero is true.
This means that the loop will continue until cnt is zero, and then the loop will end. However that's not the whole story, since the post-decrement operator is used the value of cnt after the loop have ended will be -1.
It is similar to
while(cnt--)
{
pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
dp += sz;
}
hope this is helpful.
So syntax for for loop is
for (<initialization(optional)>; <condition(Optional)>; <increment(Optional)>)
{
...
}
Say for cnt is 2 your loop works as follows,
for(; cnt--; dp+=size)
{
...
}
Execution flow is,
1. initialization statement will be executed once. Since you dont have one nothing will be executed
2. Next condition statement will be executed. In your case cnt-- which result in cnt value is considered as condition result. So, if cnt is 2 then value 2 is considered as condition result. Hence all non-zero are considered as TRUE and zero is considered as FALSE. After evaluating to TRUE it decrements cnt by 1
3. Once the condition results in TRUE then it executes the statement part say, pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
4. At the last it executes the increment statement of for loop,in you case it is dp-=size;
5. It executes from 2 till condition evaluated to ZERO ie FALSE it comes out of loop.
In c++, the value for a condition being true or false is determined by being non 0 (true) or 0 (false).
The above loop would continue iterating as long as cnt is NOT 0. It will terminate when cnt becomes 0.
UPDATE:
To clear an important point here, it is the value 0 that terminates the loop. If for some reason, cnt already starts with a negative value, the loop will never terminate