Reputation: 33
static void Main(string[] args)
{
double x;
for (x = 0; x < 5; x++)
{
Console.WriteLine(x);
}
Console.WriteLine(x);
}
My code prints out this as a result of the for loop: 0 1 2 3 4
and the
Console.WriteLine(x);
which is outside the loop prints the value 5. Why is it incrementing x by 1 outside the loop?
Upvotes: 3
Views: 142
Reputation: 15320
It is because the for
is still being executed on the 5th time.
But it doesn't enter it since x<5
is being evaluated to false
.
That is why in most cases a variable that has been defined inside a for
loop isn't going to be used after it.
Upvotes: 5
Reputation: 4202
In the last cycle x equals to 5 because it was icremented but didn't pass the check x<5
. That's why it prints 5 in the end.
I found a similar example on MSDN. I adapted the explanation to your example.
- First, the initial value of variable i is established. This step happens only once, regardless of how many times the loop repeats. You can think of this initialization as happening outside the looping process.
To evaluate the condition
i < 5
, the value ofi
is compared to5
.
If
i
is less than5
, the condition evaluates to true, and the following actions occur: TheConsole.WriteLine
statement in the body of the loop displays the value ofi
. The value of i is incremented by1
. The loop returns to the start of step 2 to evaluate the condition again.If i is greater than or equal to
5
, the condition evaluates to false, and you exit the loop.
Upvotes: 2
Reputation: 2469
The value was already increased to 5 the memory hold at last. And no any further check was made outside the loop
Upvotes: 0
Reputation: 244
The loop increments x each iteration, and breaks out only when it is not < 5. Hence to break out of the loop it must logically be 5.
Upvotes: 1