C语言 C'for'循环中的多个条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16859029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:31:09  来源:igfitidea点击:

Multiple conditions in a C 'for' loop

cfor-loop

提问by Prateek

I came across this piece of code. I generally use '&&' or '||' to separate multiple conditions in a forloop, but this code uses commas to do that.

我遇到了这段代码。我通常使用 '&&' 或 '||' 在for循环中分隔多个条件,但此代码使用逗号来做到这一点。

Surprisingly, if I change the order of the conditions the output varies.

令人惊讶的是,如果我改变条件的顺序,输出会发生变化。

#include<stdio.h>

int main() {
    int i, j=2;

    for(i=0; j>=0,i<=5; i++)
    {
         printf("%d ", i+j);
         j--;
    }
    return 0;
}

Output = 2 2 2 2 2 2

输出 = 2 2 2 2 2 2

#include<stdio.h>

int main(){
    int i, j=2;

    for(i=0; i<=5,j>=0; i++)
    {
         printf("%d ", i+j);
         j--;
    }
    return 0;
}

Output = 2 2 2

输出 = 2 2 2

Can somebody explain the reason? It seems to be checking only the last comma-separated condition.

有人可以解释原因吗?它似乎只检查最后一个逗号分隔的条件。

回答by

The comma operator evaluates all its operands and yields the value of the last one. So basically whichever condition you write first,it will be disregarded, and the secondone will be significant only.

逗号运算符计算其所有操作数并产生最后一个的值。所以基本上无论你写哪个条件它都会被忽略,第二个只会有意义。

for (i = 0; j >= 0, i <= 5; i++)

is thus equivalent with

因此等价于

for (i = 0; i <= 5; i++)

which may or may not be what the author of the code intended, depending on his intents - I hope this is not production code, because if the programmer having written this wanted to express an AND relation between the conditions, then this is incorrect and the &&operator should have been used instead.

这可能是也可能不是代码作者的意图,这取决于他的意图 - 我希望这不是生产代码,因为如果编写此代码的程序员想要表达条件之间的 AND 关系,那么这是不正确的,并且&&应该改用运算符。

回答by ShinTakezou

Of course it is right what you say at the beginning, and C logical operator&&and ||are what you usually use to "connect" conditions (expressions that can be evaluated as true or false); the comma operator is not a logical operator and its use in that example makes no sense, as explained by other users. You can use it e.g. to "concatenate" statements in the for itself: you can initialize and update j altogether with i; or use the comma operator in otherways

当然,你一开始说的没错,C逻辑运算符&&||你通常用来“连接”条件(可以评估为真或假的表达式);正如其他用户所解释的那样,逗号运算符不是逻辑运算符,并且在该示例中使用它没有任何意义。例如,您可以使用它在 for 自身中“连接”语句:您可以使用 i 初始化和更新 j;或以其他方式使用逗号运算符

#include <stdio.h>

int main(void)  // as std wants
{
  int i, j;

  // init both i and j; condition, we suppose && is the "original"
  // intention; update i and j
  for(i=0, j=2; j>=0 && i<=5; i++, j--)
  {
       printf("%d ", i+j);
  }
  return 0;        
}

回答by abelenky

The comma expression takes on the value of the last(eg. right-most) expression.

逗号表达式采用最后一个(例如最右边)表达式的值。

So in your first loop, the only controlling expression is i<=5; and j>=0is ignored.

所以在你的第一个循环中,唯一的控制表达式是i<=5; 并被j>=0忽略。

In the second loop, j>=0controls the loop, and i<=5is ignored.

在第二个循环中,j>=0控制循环,并被i<=5忽略。



As for a reason... there is no reason. This code is just wrong. The first part of the comma-expressions does nothingexcept confuse programmers. If a serious programmer wrote this, they should be ashamed of themselves and have their keyboard revoked.

至于理由……没有理由。这段代码是错误的。逗号表达式的第一部分除了迷惑程序员之外什么做。如果一个认真的程序员写了这个,他们应该为自己感到羞耻并取消他们的键盘。

回答by tafa

Wikipediatells what comma operator does:

维基百科讲述了逗号运算符的作用:

"In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type)."

“在 C 和 C++ 编程语言中,逗号运算符(由 token 表示,)是一个二元运算符,它计算第一个操作数并丢弃结果,然后计算第二个操作数并返回此值(和类型)。”

回答by Lee Daniel Crocker

Do not use this code; whoever wrote it clearly has a fundamental misunderstanding of the language and is not trustworthy. The expression:

不要使用此代码;写它的人显然对语言有根本的误解,不值得信赖。表达方式:

j >= 0, i <= 5

evaluates "j >= 0", then throws it away and does nothing with it. Then it evaluates "i <= 5" and uses that, and only that, as the condition for ending the loop. The comma operator canbe used meaningfully in a loop condition when the left operand has side effects; you'll often see things like:

计算“j >= 0”,然后将其扔掉,不做任何处理。然后它评估“i <= 5”并使用它作为结束循环的条件。当左操作数有副作用时,可以在循环条件中有意义地使用逗号运算符;你会经常看到这样的事情:

for (i = 0, j = 0; i < 10; ++i, ++j) . . .

in which the comma is used to sneak in extra initialization and increment statements. But the code shown is not doing that, or anything else meaningful.

其中逗号用于潜入额外的初始化和增量语句。但是显示的代码并没有这样做,或者其他任何有意义的事情。

回答by Robert S. Barnes

There is an operator in C called the comma operator. It executes each expression in order and returns the value of the last statement. It's also a sequence point, meaning each expression is guaranteed to execute in completely and in order before the next expression in the series executes, similar to &&or ||.

C 中有一个运算符称为逗号运算符。它按顺序执行每个表达式并返回最后一条语句的值。它也是一个序列点,这意味着每个表达式都保证在系列中的下一个表达式执行之前完全按顺序执行,类似于&&or ||

回答by MSN

Completing Mr. Crocker's answer, be careful about ++ or -- operators or I don't know maybe other operators. They can affect the loop. for example I saw a code similar to this one in a course:

完成克罗克先生的回答,小心 ++ 或 -- 运算符,或者我不知道其他运算符。它们会影响循环。例如,我在一门课程中看到了与此类似的代码:

for(int i=0; i++*i<-1, i<3; printf(" %d", i));

The result would be $ 1 2$. So the first statement has affected the loop while the outcome of the following is lots of zeros.

结果将是$ 1 2$。所以第一条语句影响了循环,而下面的结果是很多零。

for(int i=0; i<3; printf(" %d", i));