Reputation: 187
I wrote a for-loop without any instructions(except for the ones within the for syntax). Now, when I use a semi-colon immediately after the ending for bracket, the i variable stops at the value 4, as expected; whereas if i do not use a semi-colon, it stops at value 6. How come?
#include <iostream>
using namespace std;
int main()
{
int x=0;
int i;
for(i=0;i<=3;i++) //if the semicolon is absent here, value of x is 6
//if present, value of x is 4, as expected
x=x+i;
cout<<"x="<<x;
return 0;
}
Upvotes: 0
Views: 41
Reputation: 62769
I wrote a for-loop without any instructions
No you didn't. It had one that you intended to be after the loop. A for loop always has a statement.
Now, when I use a semi-colon immediately after the ending for bracket, the i variable stops at the value 4, as expected;
;
, on it's own, is a statement. So is {}
whereas if i do not use a semi-colon, it stops at value 6. How come?
Because it evaluates x = x + i
as the loop body.
Unlike some other languages, whitespace does not delimit blocks. You can have misleading indentation. Applying an autoformatter would give you something like
int main()
{
int x=0;
int i;
for(i=0;i<=3;i++)
x=x+i;
cout<<"x="<<x;
return 0;
}
Upvotes: 1
Reputation: 23497
With a semicolon, your code is effectively the same as
int x = 0;
int i;
i = 4;
x = x + i; // x = 0 + 4;
since the for
loop is equivalent to
for (i = 0; i <= 3; i++) { } // sets i to 4
Without semicolon:
int x = 0;
int i;
i = 0; x = x + i; // x = 0 + 0;
i = 1; x = x + i; // x = 0 + 1;
i = 2; x = x + i; // x = 1 + 2;
i = 3; x = x + i; // x = 3 + 3;
being for
loop equivalent to:
for (i = 0; i <= 3; i++) { x = x + i; }
Read some good C++ book for beginners to learn more about the language syntax.
Upvotes: 2
Reputation: 4137
Without semicolon, your code is equivalent to
for(i = 0; i <= 3; i++)
{
x = x + i;
}
With semicolon, it is a one-liner and x=x+i
is never called.
This is why in some code style guides, you are asked to always use brackets with for.
Upvotes: 1
Reputation: 16876
This here
for(i=0;i<=3;i++)
x=x+i;
Is actually the same as this:
for(i=0;i<=3;i++){
x=x+i;
}
The for
always needs a statement after it, else it won't compile. To make it clear that the second line is the statement of the loop, it is often indented this way:
for(i=0;i<=3;i++)
x=x+i;
With the semicolon the code is equivalent to this:
for(i=0;i<=3;i++){
; // does nothing, a so called "null statement"
}
x=x+i; // always happens once
Upvotes: 1