Why don't modern C++ compilers optimize away simple loops like this? (Clang, MSVC)

前端 未结 4 1004
时光说笑
时光说笑 2021-01-07 17:31

When I compile and run this code with Clang (-O3) or MSVC (/O2)...

#include 
#include 

static int con         


        
4条回答
  •  醉话见心
    2021-01-07 18:26

    That is indeed very interesting. I tried your example with MSVC 2013. My first idea was that the fact that the ++a[j] is somewhat undefined is the reason why the loop is not removed, because removing this would definetly change the meaning of the program from an undefined/incorrect semantic to something meaningful, so I tried to initialize the values before but the loops still did not dissappear.

    Afterwards I replaced the ++a[j]; with an a[j] = 0; which then produced an output without any loop so everything between the two calls to clock() was removed. I can only guess about the reason. Perhaps the optimizer is not able to prove that the operator++ has no side effects for any reason.

提交回复
热议问题