Reputation: 63
Can someone explain how the for(; A--;) loop works. It doesn't have any increments, so shouldn't it run forever ?
int main(){
int A, B;
cout << "Anna t\x84htien m\x84\x84r\x84: "; //Give ammount of stars:
cin >>A;
cout << endl;
for(; A--;){
for(B = 0; A >= B; B++){
cout << "* ";
}
cout << endl;
}
return 0;
}
Upvotes: 3
Views: 2429
Reputation: 58
In C/C++ a condition is true in every sense if it is non-zero. Let me clarify this by giving an example,
#include<iostream>
using namespace std;
int main()
{
int a=5, b=-5;
while(a)
{
cout<<"# ";
a--;
}
cout<<"\n";
while(b)
{
cout<<"* ";
b++;
}
return 0;
}
The output of the code will be:
# # # # #
* * * * *
If you look into this, inside the 'a' while loop, the condition is positive and it decrements until the value is '0'. Until the value is 0, the condition is said to be true and the flow of control executes the statements inside the while loop.
In the 'b' while loop, it is clearly visible that even if 'b' is negative, the statements inside the while loop still executes until the value of 'b' increments to 0.
It is visible that every non-zero term is considered to be a true condition and a 0(zero) is considered to be a false condition. It is a mis-belief that (only) 1 is true and 0 is false.
The syntax for for
loop is for(declaration;condition;iteration)
. If one of the statements is missing, the loop will still continue to run. A for loop
works as long as the condition is true. The flow of control, at first comes to the declaration, then checks the condition. If the condition is true, then it executes the statements in the scope of the loop. At last, the control comes to the iterative statements and again checks the condition. During the run-time, if at any moment the looping condition turns out to be false
, then the control terminates the program or executes the statements just after the loop.
Upvotes: 2
Reputation: 11
A-- is found in the condition part. As long as A != 0, the loop will execute. Since the -- operator is found after the variable, the decrement will be executed after the evaluation of A's value. Ex:
int A = 10;
//This loop will output: 9 8 7 6 5 4 3 2 1 0
for(;A--;){
std::cout<<A<<" ";
}
A = 10;
//This loop will output: 9 8 7 6 5 4 3 2 1
for(;--A;){
std::cout<<A<<" ";
}
Upvotes: 1
Reputation: 9806
It goes until A
reaches 0 and than will stop in the case that A
was >= 0
initially, otherwise, as pointed out by Eric, the behavior is undefined, as overflow will occur and it can end in few different ways.
Upvotes: 0
Reputation: 15229
A for
loop runs for as long as its condition holds true. A--
is equivalent to A-- != 0
, so this is how long it's going to run.
One thing that is possibly nice to know is that a for
loop can contain a lot more than mere incremental operations. Usually, it's something like ++i
, but that is no necessity. In school, you might not learn about how general for
loops actually are, though.
Upvotes: 5