简体   繁体   English

在C中使用赋值语句进行循环条件

[英]Using assignment statement in c for loop condition

Is statement A & B are equal? 陈述A和B是否相等?

int i;
char a[] = "Hello\n";
char b[100];    

Statement A, 报表A,

for(i=0; b[i] != '\0'; ++i)
    b[i] = a[i];

Statement B, 报表B,

for(i=0; (b[i] = a[i]) != '\0'; ++i)
      ;

No, they are different: 不,它们是不同的:

  • The first loop checks the value of b[i] before the assignment; 第一个循环在赋值之前检查b[i]的值;
  • The second loop checks the value of b[i] after the assignment. 第二个循环在分配检查b[i]的值。

As the result, the second loop will copy the content of a into b , and stop after copying \\0 . 结果,第二个循环会将a的内容复制到b ,并在复制\\0之后停止。 The first loop would stop copying as soon as it encounters the first \\0 in b before performing a copy, disregarding any zeros that it may find in a . 在执行复制之前,第一个循环一旦在b遇到第一个\\0就会停止复制,而忽略它在a可能找到的任何零。

No they are not. 不,他们不是。

In statement A, you are checking b[i] before assigning value to it 在语句A中,您正在检查b[i]然后再为其分配值

In the second statement, you are assigning value before checking. 在第二条语句中,您要在检查之前分配值。

The 1st one is like a while loop , where is the second one is like a do - while loop . 第一个就像一个while循环 ,第二个就像一个do-while循环

NO they are not the same 不,他们不一样

in the second you have set the b[i] value and then you have checked != '\\0' . 在第二秒钟中,您已经设置了b[i]值,然后检查了!= '\\0'

in the fisrt you have checked the b[i] != '\\0' before set it 在第一个字段中,您已在设置b[i] != '\\0'之前检查了它

I can suggest to you also: 我也可以建议您:

int i = -1;
while(b[++i] = a[i]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM