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

后端 未结 18 1701
再見小時候
再見小時候 2020-12-07 15:10

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
}
<         


        
18条回答
  •  既然无缘
    2020-12-07 16:05

    If ss is of type const char * and you're not casting away the constness within the loop the compiler might only call strlen once, if optimizations are turned on. But this is certainly not behavior that can be counted upon.

    You should save the strlen result in a variable and use this variable in the loop. If you don't want to create an additional variable, depending on what you're doing, you may be ale to get away with reversing the loop to iterate backwards.

    for( auto i = strlen(s); i > 0; --i ) {
      // do whatever
      // remember value of s[strlen(s)] is the terminating NULL character
    }
    

提交回复
热议问题