This reminded me of something I learned before
| |
My previous understanding of for loops was like this
When execution reaches a for loop
it first executes the initialization statement once
then it starts executing the loop body (the loop statement)
after execution, it executes the increment statement
then it evaluates the condition statement
if it holds, it continues executing loop statement → increment statement → condition statement…
But through the introduction in P19 and some experiments
I found there seem to be some points that need attention
That is, this form:
| |
That is, the loop variable i is created only at the for statement
According to the previous
When execution reaches the for loop
it first executes the initialization statement once
understanding, this i should be the same as this usage:
| |
is the same
but after investigating, I found it is not the same
Refer to the following code
| |
It reports an error when compiled
That is, after the for loop ends
i becomes inaccessible
If the commented-out statement before the for is added
I found the execution result is as follows:

It can be seen that the int i inside the loop did not affect the int i outside the loop
So it is clear that the i in this for loop is independent
In that case, since it is independent, defining it when needed should be better than defining it directly beforehand
Previously, in this kind of situation, I used to separate normal variables from loop variables
like this
| |
After learning about this feature
I can easily define these variables when using for without affecting other parts
There is a sentence in P19
Tip 2-4 It is recommended to shorten the definition scope of variables as much as possible. For example, define the loop variable in the initialization part of the for loop.
I also deeply feel this makes a lot of sense~
By the way, this is resonance~ After all, everyone’s habits are different; being able to agree with a master still makes me a little excited
Introduction to Algorithm Competition Classic (2nd Edition), P19
The above was published at:
[Reading] Defining Variables in for Loops (2016-01-04 17:11) 11 0
20160112 addendum: Follow-up article:[Reading] Follow-up discussion on defining variables in for loops(/content/post/note/competitive-programming/8/%E7%AE%97%E6%B3%95%E7%AB%9E%E8%B5%9B%E5%85%A5%E9%97%A8%E7%BB%8F%E5%85%B8(8) – %E5%85%B3%E4%BA%8Efor%E5%BE%AA%E7%8E%AF%E4%B8%AD%E5%AE%9A%E4%B9%89%E5%8F%98%E9%87%8F%E7%9A%84%E5%90%8E%E7%BB%AD%E8%AE%A8%E8%AE%BA)