执行条件为false后,for循环仍然递增

时间:2018-05-22 02:41:29

标签: c for-loop

我是C的新手所以这个问题很可能有一个简单的解决方案,但我无法看到它。我注意到我的输出不是我所期望的,经过几个小时的调试后,我意识到我的一个for循环没有按预期运行。这是我的代码的相关部分:

for (i = 0; i < bytes; i++)
        {
            if ((temp_array[i]) == 0xCADE | (temp_array[i]) == 0xDADA)
            {

                printf("i is %d\n",i );
                i += 2;

                printf("i is now %d\n",i );

                n_body = temp_array[i];

                i++;

                printf("n_body is %d\n",n_body );

                for (count = 0, j = flag_index; count < n_body; i++, j++, count++)
                {

                    machine->memory[j] = temp_array[i];
                    printf("LETS SEE, i in loop is %d\n",i );
                    printf("LETS SEE, j in loop is %d\n",j );
                    printf("LETS SEE, count in loop is %d\n", count);

                }

                printf("\n");
                printf("LETS SEE, i out of loop is %d\n",i );
                printf("LETS SEE, j out of loop is %d\n",j );
                printf("LETS SEE, count out of loop is %d\n", count);

                machine->memory[j+1] = flag;

                //printf("flag is %d\n",flag );
                printf("machine memory index 18 is %d \n", machine->memory[18]);

            }

            // else
            // {
            //  continue;
            // }

            //printf("index is %d\n",i );
        }

罪魁祸首是第二个(嵌套)for循环。我注意到,一旦执行条件count < n_body不再为真,变量i,j和count就会递增。在此特定点,n_body为18,i为3,bytes为64,flag_index为0.我发布了最后几次迭代的输出for循环和for循环外的print语句的输出:

LETS SEE, i in loop is 18
LETS SEE, j in loop is 15
LETS SEE, count in loop is 15
LETS SEE, i in loop is 19
LETS SEE, j in loop is 16
LETS SEE, count in loop is 16
LETS SEE, i in loop is 20
LETS SEE, j in loop is 17
LETS SEE, count in loop is 17

LETS SEE, i out of loop is 21
LETS SEE, j out of loop is 18
LETS SEE, count out of loop is 18

他们为什么递增?一旦执行条件不再成立,我认为for循环关闭(执行主体和前置增量)?

1 个答案:

答案 0 :(得分:3)

这很正常。您可以通过一个小型演示程序看到。

#include <stdio.h>

int main() {
    int i = 0;
    for( i = 0; i < 3; i++ ) {
        printf("i in loop: %d\n", i);
    }

    printf("i after loop: %d\n", i);
}

$ ./test
i in loop: 0
i in loop: 1
i in loop: 2
i after loop: 3

标准的相关部分是:

  

6.8.5.3 for陈述

     

1声明

     

for ( clause-1 ; expression-2 ; expression-3 ) statement

     

的行为如下:表达式表达式-2是在每次执行循环体之前计算的控制表达式。 每次执行循环体后,表达式-3将被计算为void表达式。

每次身体执行时,都会发生增量。如果正文运行三次,那就是i++的三次迭代。

你也可以想到像这样的for循环。

// for( int i = 0; i < 3; i++ ) {
int i = 0;
while( i < 3 ) {
    printf("i in loop: %d\n", i);
    i++;
}

所以你的内循环相当于..

// for (count = 0, j = flag_index; count < n_body; i++, j++, count++) {
count = 0, j = flag_index;
while( count < n_body ) {                
    machine->memory[j] = temp_array[i];
    i++, j++, count++;
}