return list of values between parenthesis (10, 20, 30, 40)?

后端 未结 4 1236
自闭症患者
自闭症患者 2020-12-06 14:23

I am working in C++ (not C++/CLI) in Visual Studio 2012.

I don\'t understand why this code works, I would have expected it to fail

4条回答
  •  余生分开走
    2020-12-06 15:12

    This is using the comma operator which will evaluate each expression from left to right but only return the last. If we look at the draft C++ standard section 5.18 Comma operator it says:

    A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded value expression (Clause 5).83 Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression.

    the linked article gives the most common use as:

    allow multiple assignment statements without using a block statement, primarily in the initialization and the increment expressions of a for loop.

    and this previous thread Uses of C comma operator has some really interesting examples of how people use the comma operator if you are really curious.

    Enabling warning which is always a good idea may have helped you out here, in gcc using -Wall I see the following warning:

    warning: left operand of comma operator has no effect [-Wunused-value]
      return (10, 20, 30, 40);
                  ^
    

    and then two more of those.

提交回复
热议问题