int i, j;
for (i=0, j=5; i=j;)
{
cout<<i<<j<<endl;
i++;
j--;
}
It executes five times:
55
44
33
22
11
When j=0, why does it stop?
for (i=0, j=5; i=j;)
sets i to j before every iteration. So the loop breaks as soon as j == 0 which happens after you decreased j five times. An integer converted to a boolean expression results in false if it is zero, and true otherwise.
Note the difference between = (assignment) and == (comparison).
The expression i=j evaluates to the value of i after the assignment. And a zero value is false when evaluated in a boolean context. So whenever i is assigned the value 0, the loop condition is false and the loop stops.
Related
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.
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.
Sorry for a probably stupid question.
My loop does not stop at 0 and I have no idea why.
This loop will stop at i = 1
for (unsigned int i = 3 ; i > 0 ; i--)
Whereas this will stop at i = 4294967295 instead
for (unsigned int i = 3 ; i >= 0 ; i--)
Why? Do I miss anything?
In fact this i >= 0 for unsigned int is always true. So you cannot use it as loop invariant.
Use this instead:
for (unsigned int i = 4 ; i-- > 0 ;)
println(i);
it will print 3,2,1,0
A for loop iterates until the break condition evaluates to false.
In your case the loop will repeatedly check:
is i>0 (i>=0 respectively) true? If so, execute body and decrement i, else skip the loop-body.
Your first loop will at some point reach i=1. i>0 will evaluate to true. The body will be executed, i will be decremented. i will then be 0. Hence i>0 will evaluate to false and the body will not be executed and you will break out of the loop.
Your second loop will not stop (tested with g++). Why? Your i will reach 0. i>=0 will evaluate to true. The body will be executed, i will be decremented. But since you are using an unsigned int this will then assign 4294967295 to i. Since 4294967295>=0, the loop will continue, reach 0 again and again assign 4294967295 to i thus executing indefinitely.
This happens since an unsigned int represents 0 as all 0s in binary and subtracting 1 from it will yield all 1s which is interpreted as 4294967295.
How to avoid the problem? As mentioned in the comments a simple way out of it would be to use an int instead of an unsigned int.
char i;
for (i = 1; i < 10, i++;)
{
cout << (i+1) << endl;
}
return 0;
I understand that for loop has the following syntax:
for(initialization; condition; increment)
{
}
As I run the debug, why it never checks the condition and it eventually stops at i = 0?
(Thank you Damien and Andars, I don't know why the "on purpose" statement was removed, but you interpret my question correctly. Could someone explain why the complier skips the condition before the comma, and why the loop stop at i = 0 instead of looping forever? Thanks!)
I believe he is indicating that he wrote the code that way on purpose.
To answer, i++ will always return true. The last value is the value that matters with comma separated statements, so the loop will not stop.
Edit for elaborations:
It isn't simply using a logical or, it disregards what is before the comma and only takes the last value. The value of anything non-zero is considered true, and since i starts at 1, and goes up, it will always be non-zero (until it overflows and wraps back around, which explains why i ends at 0).
If you say:
x = 4, 5, 6;
x will be equal to 6, the last value.
Change
for (i = 1; i < 10, i++;)
to
for (i = 1; i < 10; i++)
Change to
for (i = 1; i < 10; i++) //Notice correct placement of ;
It seems to me also that the code was written incorrectly on purpose. As others have mentioned, the comma operator will discard the value of the i<10 and only i++ will be evaluated as condition. This will return true until i overflows (values only from -127 to 127) and ends up at -1, when i++ will return 0 and the loop exits. Thus the final value for i will be 0.
Because you used the comma operator instead of a semi-colon
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