Does Visual C++ consider signed integer overflow undefined?

后端 未结 2 1168
梦毁少年i
梦毁少年i 2021-02-19 19:08

It\'s gotten a lot of attention lately that signed integer overflow is officially undefined in C and C++. However, a given implementation may choose to define it; in C++, an i

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-19 19:36

    Found an interesting tidbit from back 2016 (VS2015 Update 3):

    They talk about the new SSA optimizer they want to introduce into VS2015:

    C++ Team Blog - Introducing a new, advanced Visual C++ code optimizer

    ... ... ...

    Historically, Visual C++ did not take advantage of the fact that the C and C++ standards consider the result of overflowing signed operations undefined. Other compilers are very aggressive in this regard, which motivated the decision to implement some patterns which take advantage of undefined integer overflow behavior. We implemented the ones we thought were safe and didn’t impose any unnecessary security risks in generated code.

    So there you have it. I read that as: "we never programmed in any extra bits to make use of this UB", but starting from VS2015/Update3 we will have some.

    I should note that even before that I'd be extremely wary, because for 64 bit code and 32bit variables, if the compiler/optimizer simply puts the 32bit signed int into a 64bit register, you'll have undefined no matter what. (As shown in "How not to code: Undefined behavior is closer than you think" - unfortunately, it's unclear from the blog post whether he used VS2015 pre or post Update3.)

    So my take on this whole affair is that MSVC always considered it UB, even though past optimizer version did not take special advantage of the fact. The new SAA optimizer seems to do for sure. (would be interesting to test if the –d2UndefIntOverflow– switch does it's job.)

提交回复
热议问题