[英]On the difference between “for(a, b&&c, d) {…}” and “for(a, b, d) if(c) {…}”
As a programmer of long standing, it's sobering to realise that even the humble for
loop is not fully comprehended. 作为一个长期的程序员,认识到即使是谦虚的for
循环也没有被完全理解是很清醒的。 Why does the following program print a single 1
to the console? 为什么以下程序将单个1
打印到控制台? I fully expect the first loop to also produce a 1
! 我完全希望第一个循环也产生一个1
! Compiled with -ansi
switch. 与-ansi
开关一起编译。
/* gcc installed version: 4:4.4.4-1ubuntu2 */
#include <stdio.h>
#define SIZE 2
int main()
{
int i;
int a[SIZE];
a[0]=0;
a[1]=1;
for(i=0; (i<SIZE) && (a[i]!=0); i++)
printf("%i\n",a[i]);
for(i=0; i<SIZE; i++)
if (a[i]!=0)
printf("%i\n",a[i]);
return 0;
}
the first loop is equivalent to: 第一个循环等效于:
for(i=0; ; i++) {
if( !((i<SIZE) && (a[i]!=0)))
break;
printf("%i\n",a[i]);
}
It's the difference between this: 两者之间的区别在于:
for(i=0; i<SIZE; i++)
if (a[i]!=0)
printf("%i\n",a[i]);
else
continue; // implicit in your version with the if statement
and this: 和这个:
for(i=0; i<SIZE; i++)
if (a[i]!=0)
printf("%i\n",a[i]);
else
break; // equivalent of what the non if statement version does.
(Credit goes to @ta.speot.is for actually spotting the problem, this is merely an explanation) (由于实际发现了问题,信用去@ ta.speot.is,这只是一个解释)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.