为什么相同的循环体次数,for循环明显更快执行完毕?

#include <reg51.h>

void delay(void) { //while循环方式 unsigned char i=200; unsigned char j=200; while (i--) while(j--); /* //for循环方式 unsigned char i = 200; unsigned char j = 200; for (i=200 ;i>0;i--) for(j=200; j>0 ;j--); */ }

void main(void) { while(1) { unsigned char p = 0x01; unsigned char q; for ( q = 0 ; q < 8 ; q++) { P0 = ~(p << q); delay(); }

}

}

c
86 views
Comments
登录后评论
Sign In
·

因为两份代码并不等价

根据题主的代码写一个 test:

#include <stdio.h>

void delay_while() {
    puts("while:");
    unsigned char i = 200;
    unsigned char j = 200;
    while (i--)
        while(j--)
            printf("%d %d\n", i, j);
}

void delay_for() {
    puts("for:");
    unsigned char i = 200;
    unsigned char j = 200;
    for (i = 200; i > 0; i--)
        for(j = 200; j > 0; j--)
            printf("%d %d\n", i, j);
}

int main() {
    freopen("while.out", "w", stdout);
    delay_while();
    freopen("for.out", "w", stdout);
    delay_for();
    return 0;
}

int main() {
    delay_while();
    delay_for();
    return 0;
}

输出文件中,while.out50947 行,for.out40002 行。