问题
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