简体   繁体   English

While 循环的参数内的逗号

[英]Comma inside arguments of While Loop

Studying for a computer science final.为计算机科学期末考试而学习。

I really cannot figure this question out.我真的想不通这个问题。

What will be the output of this C program?这个 C 程序的输出是什么?

#include<stdio.h>
int main()
{
    int i = 0;
    while(i < 4, 5)
    {
        printf("Loop ");
        i++;
    }
    return 0;
}

A. Infinite Loop A.无限循环

B. Loop Loop Loop Loop Loop B. Loop Loop Loop Loop Loop

C. Loop Loop Loop Loop C. Loop Loop Loop Loop

D. Prints Nothing D.什么都不打印

Upon execution it prints loop for infinite times.执行时,它会无限次打印循环。 Why is that happening?为什么会这样? Why is there a comma inside the arguments of While loop?为什么While循环的参数里面有一个逗号? What does it do?它有什么作用?

What you have in the while loop's condition is the comma operator , which evaluates its operands and yields the value of its right most operand.你在 while 循环的条件中拥有的是逗号 operator ,它评估其操作数并产生其最右边操作数的值。

In your case, it evaluates i < 4 condition and discards it and then evaluates the condition to just 5. So it's essentially equivalent to:在您的情况下,它评估i < 4条件并丢弃它,然后将条件评估为 5。所以它本质上等同于:

while(5)
{
    printf("Loop ");
    i++;
}

Which obviously results in infinite loop as the condition is always true.这显然会导致无限循环,因为条件始终为真。 (remember that any non-zero value is always "true" in C). (请记住,任何非零值在 C 中始终为“真”)。 There's also a possible integer overflow due to i getting incremented in the infinite loop.由于i在无限循环中递增,也可能出现整数溢出

It will loop forever, because the condition of the while loop i < 4, 5 evaluates to 5 , which is different than 0, therefore is considered true in C .它将永远循环,因为 while 循环的条件i < 4, 5求值为5 ,它不同于 0,因此在C被认为是true

To learn more about that, read about the comma operator : https://en.wikipedia.org/wiki/Comma_operator要了解更多信息,请阅读comma operatorhttps : //en.wikipedia.org/wiki/Comma_o​​perator

Briefly, when the comma operator is used, all of its operands are evaluated but the whole expression takes the value of the last one.简而言之,当使用逗号运算符时,它的所有操作数都会被计算,但整个表达式采用最后一个的值。 For example:例如:

int val = (1, 2, 3);
printf("%d\n", val);

Will print 3 .将打印3

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

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