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

后端 未结 6 1418
忘了有多久
忘了有多久 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:14

    I would like to point out one thing: a[i] = i does not always lead to well defined behaviour. The reason why the behaviour is well defined in the case specified, is because of the initial values i and a.

    Let me elaborate:

    int i = 1, *a = &i;   // Line 1, i initialized to anything other than 0
    a[i] = i + 1;         // Line 2, all of a sudden we are in buffer over/underflow
    

    For any other initial value of i we are accessing a different memory location from that of i itself, which produces undefined behaviour.

提交回复
热议问题