简体   繁体   English

关于“ for(a,b && c,d){…}”和“ for(a,b,&d)if(c){…}”之间的区别

[英]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.

相关问题 在 c 语言中将二维数组传递给 function,int* b[4] 和 int b[][4] 有什么区别? - passing a 2d-array to a function in c language, what is the difference between int* b[4] and int b[][4]? 如果A == B && B == C && C == D,有更好的方法吗? - Is there a better way to do if A==B && B==C && C==D? 参数c [a] [b]和c [] [2]有什么区别 - What is the difference between the parameter c[a][b] and c[][2] 指针的指针:* a = b-&gt; c和a =&b-&gt; c之间的差异 - Pointers to pointers: Difference between *a = b->c and a = &b->c 这段代码如何工作&#39;printf(“%d%d%d \\ n”,(a,b,c));&#39; - how this code works 'printf(“%d %d %d\n”,(a,b,c));' 是否保证解析为“(a?b:(c?d:e))”? - Is it guaranteed to parse as a “(a ? b : (c ? d : e))”? c语言中%d和%*d有什么区别? - What is the difference between %d and %*d in c language? C 语言中 %d 和 %.d 的区别 - Difference between %d and %.d in C language 为什么流水线工作对于(a + b)+(c + d)比对+ b + c + d更好? - Why might pipelining work better for (a+b)+(c+d) than for a+b+c+d? 如何计算(a * b * c * d / e)%m f a,b,c,d,e是10 ^ 18的阶数? - How to calculate (a*b*c*d/e)%m f a,b,c,d,e are of order 10^18?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM