Does 'a[i] = i;' always result in well defined behaviour?

后端 未结 6 1406
忘了有多久
忘了有多久 2021-02-05 11:19

There are several interesting questions raised here regarding undefined behaviour in C. One of them is (slightly modified)

Does the following piece of code r

6条回答
  •  粉色の甜心
    2021-02-05 12:06

    Let us decompose the expression a[i] = i + 1 will you ?

    = -- [] -- a
      \     \_ i
       \
        \_ + -- i
             \_ 1
    

    Effectively, a[i] refers to &i however note that neither a[i] nor i+1 modifies i. i is only modified when = (the assignment itself) is executed.

    Since the operands of any function need be evaluated before this function takes effect, this is actually equivalent to:

    void assign(int& address, int value) { address = value; }
    
    assign(a[i], i + 1);
    

    It is true that = is somewhat special in that it is built-in and does not result in a function call, still the evaluation of both operands are sequenced before the actual assignment, so they are first evaluated prior to i being modified, and a[i] (which points to i location) is being assigned to.

提交回复
热议问题