c++cgccoptimizationstrlen

Will strlen be calculated multiple times if used in a loop condition?


I'm not sure if the following code can cause redundant calculations, or is it compiler-specific?

for (int i = 0; i < strlen(ss); ++i)
{
    // blabla
}

Will strlen() be calculated every time when i increases?


Solution

  • Yes, strlen() will be evaluated on each iteration. It's possible that, under ideal circumstances, the optimiser might be able to deduce that the value won't change, but I personally wouldn't rely on that.

    I'd do something like

    for (int i = 0, n = strlen(ss); i < n; ++i)
    

    or possibly

    for (int i = 0; ss[i]; ++i)
    

    as long as the string isn't going to change length during the iteration. If it might, then you'll need to either call strlen() each time, or handle it through more complicated logic.