Why is i = v[i++] undefined?

后端 未结 8 1479
生来不讨喜
生来不讨喜 2021-02-01 13:41

From the C++ (C++11) standard, §1.9.15 which discusses ordering of evaluation, is the following code example:

void g(int i, int* v) {
    i = v[i++]; // the beha         


        
8条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-01 14:15

    Think about the sequences of machine operations necessary for each of the following assignment statements, assuming the given declarations are in effect:

    extern int *foo(void);
    extern int *p;
    
    *p = *foo();
    *foo() = *p;
    

    If the evaluation of the subscript on the left side and the value on the right side are unsequenced, the most efficient ways to process the two function calls would likely be something like:

    [For *p = *foo()]
    call foo (which yields result in r0 and trashes r1)
    load r0 from address held in r0
    load r1 from address held in p
    store r0 to address held in r1
    
    [For *foo() = *p]
    call foo (which yields result in r0 and trashes r1)
    load r1 from address held in p
    load r1 from address held in r1
    store r1 to address held in r0
    

    In either case, if p or *p were read into a register before the call to foo, then unless "foo" promises not to disturb that register, the compiler would need to add an extra step to save its value before calling "foo", and another extra step to restore the value afterward. That extra step might be avoided by using a register that "foo" won't disturb, but that would only help if there were a such a register which didn't hold a value needed by the surrounding code.

    Letting the compiler read the value of "p" before or after the function call, at its leisure, will allow both patterns above to be handled efficiently. Requiring that the address of the left-hand operand of "=" always be evaluated before the right hand side would likely make the first assignment above less efficient than it otherwise could be, and requiring that the address of the left-hand operand be evaluated after the right-hand side would make the second assignment less efficient.

提交回复
热议问题