Can C++ compilers optimize “if” statements inside “for” loops?

后端 未结 7 1864
闹比i
闹比i 2020-12-09 03:09

Consider an example like this:

if (flag)
  for (condition)
    do_something();
else
  for (condition)
    do_something_else();

If fla

7条回答
  •  盖世英雄少女心
    2020-12-09 03:28

    I'm sure if the compiler can determine that the flag will remain constant, it can do some shufflling:

    const bool flag = /* ... */;
    for (..;..;..;)
    {
        if (flag)
        {
            // ...
        }
        else
        {
            // ...
        }
    }
    

    If the flag is not const, the compiler cannot necessarily optimize the loop, because it can't be sure flag won't change. It can if it does static analysis, but not all compilers do, I think. const is the sure-fire way of telling the compiler the flag won't change, after that it's up to the compiler.

    As usual, profile and find out if it's really a problem.

提交回复
热议问题