Introduction to Algorithm Competitions (6) – Defining Variables in for Loops

Words: 433

This reminded me of something I learned before

cpp
1
2
3
for(起始语句;判断语句;修正语句){
循环语句;
}

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:

cpp
1
for(int i=0; i<100; i++);

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:

cpp
1
2
int i;
for(i=0; i<100; i++);

is the same
but after investigating, I found it is not the same

Refer to the following code

cpp
1
2
3
4
5
6
7
8
#include<stdio.h>
int main() {
//  int i;
    for(int i=0; i<20; i++)
        printf("%d ",i);
    printf("\n%d",i);
    return 0;
}

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:

image.png

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

cpp
1
2
int n,m,x,y; //储存数值的变量
int i,j,k;  //记录循环次数的变量

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)

Loading...