“x = ++x” is it really undefined?

前端 未结 6 809
悲&欢浪女
悲&欢浪女 2020-12-16 15:50

I am using Coverity Prevent on a project to find errors.

It reports an error for this expression (The variable names are of course changed):

x=
   (a         


        
6条回答
  •  天命终不由人
    2020-12-16 16:20

    It is hard to imagine a compiler producing code for "x = ++x;" which would in fact not work the same as "++x". If x is not volatile, however, it would be legal for a compiler to process the statement "y = ++x;" as

      y=x+1;
      x=x+1;
    

    The statement "x = ++x;" would thus become

      x=x+1;
      x=x+1;
    

    If having the destination of one an arithmetic assignment expression get used too quickly as a source operand for another would cause a pipeline delay, the former optimization might be reasonable. Obviously disastrous if the incremented and assigned variable are one and the same.

    If variable 'x' is volatile, I can't think of any code sequence where a compiler that wasn't deliberately trying to be mean could legitimately regard "x = x++;" as having any effect other than reading all parts of 'x' exactly once and writing the same correct value to all parts of 'x' exactly twice.

提交回复
热议问题