Why is this Undefined Behavior?

前端 未结 3 826
我在风中等你
我在风中等你 2021-01-13 10:29

Why does the following given expression invoke undefined behavior?

int i = 5;
i = (i,i++,i) + 1 

My question is influenced by Als\' questio

3条回答
  •  心在旅途
    2021-01-13 11:21

    It isn't undefined.

    Answered here for C, Sequence points and partial order

    I think the same applies in C++ (and here's my response before I saw that link):

    The comma operator introduces a sequence point (and constrains to some extent the order in which the expression must be evaluated - left before right), so:

    • the two modifications of i are separated by a sequence point (the second comma).
    • the modification of i in i++ is separated from everything else by sequence points.
    • the modification of i by = is not separated from the last occurrence of i in the expression, but that's OK because we're allowed to access i and modify it without an intervening sequence point, provided that the access is "to determine the value to be stored" (5/4).
    • As Als says, in practice it wouldn't matter whether that code has defined behavior or not provided that everyone had the basic common sense not to write it ;-)

提交回复
热议问题