简体   繁体   中英

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?

#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?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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