Comma inside arguments of While Loop

老子叫甜甜 提交于 2021-01-29 08:23:12

问题


Studying for a computer science final.

I really cannot figure this question out.

What will be the output of this C program?

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

A. Infinite Loop

B. Loop Loop Loop Loop Loop

C. Loop Loop Loop Loop

D. Prints Nothing

Upon execution it prints loop for infinite times. Why is that happening? Why is there a comma inside the arguments of While loop? What does it do?


回答1:


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.

To learn more about that, read about the comma operator: https://en.wikipedia.org/wiki/Comma_operator

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.




回答2:


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.

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:

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). There's also a possible integer overflow due to i getting incremented in the infinite loop.



来源:https://stackoverflow.com/questions/54851766/comma-inside-arguments-of-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!