jeudi 30 juillet 2020

Is the if-statement with a const condition optimized inside a for loop (c++)

Consider the following code:

void func(int a, size_t n)
{
  const bool cond = (a==2);
  if (cond){
    for (size_t i=0; i<n; i++){
      // do something small 1
      // continue by doing something else.
    }
  } else {
    for (size_t i=0; i<n; i++){
      // do something small 2
      // continue by doing something else.
    }
  }
}

In this code the // continue by doing something else. (which might be a large part and for some reason cannot be separated into a function) is repeated exactly the same. To avoid this repetition one can write:

void func(int a, size_t n)
{
  const bool cond = (a==2);
  for (size_t i=0; i<n; i++){
    if (cond){
      // do something small 1
    } else {
      // do something small 2
    }
    // continue by doing something else.
  }
}

Now we have an if-statement inside a (let's say very large) for-loop. But the condition of the if-statement (cond) is const and will not change. Would the compiler somehow optimize the code (like change it to the initial implementation)? Any tips? Thanks.

Aucun commentaire:

Enregistrer un commentaire