For loop condition (cpp) - c++

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

Related

Does while loop consider zero 0 as a False Condition

I have a Question About While Loop.
int space = 4;
while(space){
cout<< "*";
space --;
}
This While Loop will run 4 times and stop when value reaches to Zero 0, So my Question is we do not specify any condition like while(space > 0){...} then why it Stop.
Or this Zero 0 consider as False , and first our while loop is true and when Reaches to 0 it becomes False and Stop.
Please Tell me , i am little confused about it.
int gets converted to bool in a boolean context using space != 0.
The while loop takes a condition which is a bool. In this case, you've passed in an int instead, which will get implicitly converted to bool. That bool will be false if the int is 0, and will be true for any other value.

C for loop syntax understanding

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

How is this for loop terminated?

Found as a user submission on leetcode for the problem Plus One.
vector<int> plusOne(vector<int>& digits) {
for (int i=digits.size(); i--; digits[i] = 0)
if (digits[i]++ < 9)
return digits;
digits[0]++;
digits.push_back(0);
return digits;
}
Normally there's something in the conditional like i >= 0; How is this for loop terminating and not accesing some -i element?
A for loop terminates when the second expression is false or when contextually converted to a bool value produces false. In C++, 0 is contextually converted to false; all other integers convert to true in a bool context. (Thanks to M.M.for the link.)
So at the beginning of each loop the expression i-- is evaluated. It's just an expression, so it will produce a result. If the result it produces is zero, the loop will end. If you haven't seen this expression before, here is how it works:
It both decrements i and returns the original value of i before it was decremented. So if i were 5, evaluating i-- will have the "result" 5, but as a side effect, i will be 4 after the evaluation.
The big picture: i is decremented by 1 each time, so assuming it starts off positive, it will get down to 0, at which time evaluating i-- will produce 0.

Do while with a boolean as the condition in c++?

so i want to know how a boolean acts in a condition statement in the following code
bool flag = true;
do {
d += data[i];
if (d > 15 || i == 3) {
flag = false;
}
i = i + 1;
} while (flag);
when will it exit the dowhile loop?
If either d > 15 or i == 3 evaluates to true, i will get incremented and the loop will stop.
In other words, flag is only checked at the end of each iteration, even though it might be set to false in the middle of one.
It will exit when (d > 15 || i == 3) which means (d > 15 or i == 3).
i is incremented at each iteration therefore if i is < 3 at the beginning of the program we are sure that at a certain point it will reach i == 3 and break the loop.
On d we can't tell much since we don't know it initial value nor its behavior inside the loop since we don't know anything about data.
Depends on your values of d and i...
As soon as d is greater than 15 or i is equal to 3, flag becomes false and the loop will end.
This might not happen in the same iteration, though. For example if i is incremented to 3 in a loop, it will be evaluated in the following loop first and flag might be set to false.
It will break the while when SUM of first 3 values in array Data[] be greater than "15", or break if does not be greater than 15 the SUM of first 3 values.
[It's depend on initial value of "i"]

What does "for(;;)" mean?

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 ; } }