Assigning value in while loop condition

前端 未结 5 1926
鱼传尺愫
鱼传尺愫 2020-12-25 08:18

I found this piece of code on Wikipedia.

#include 

int main(void)
{
  int c;

  while (c = getchar(), c != EOF && c != \'x\')
  {
           


        
5条回答
  •  鱼传尺愫
    2020-12-25 08:50

    The comma operator is a weird beastie until you get to understand it, and it's not specific to while.

    The expression:

    exp1, exp2
    

    evaluates exp1 then evaluates exp2 and returns exp2.

    You see it frequently, though you may not realize it:

    for (i = j = 0; i < 100; i++, j += 2)
    

    You're not actually using the return value from "i++, j += 2" but it's there nonetheless. The comma operator evaluates both bits to modify both i and j.

    You can pretty well use it anywhere a normal expression can be used (that comma inside your function calls is not a comma operator, for example) and it's very useful in writing compact source code, if that's what you like. In that way, it's part of the family that allows things like:

    while ((c= getchar()) != EOF) {...}
    i = j = k = 0;
    

    and so on.

    For your specific example:

    while (c = getchar(), c != EOF && c != 'x')
    

    the following occurs:

    • c = getchar() is executed fully (the comma operator is a sequence point).
    • c != EOF && c != 'x' is executed.
    • the comma operator throws away the first value (c) and "returns" the second.
    • the while uses that return value to control the loop.

提交回复
热议问题