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

后端 未结 18 1704
再見小時候
再見小時候 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 15:47

    Elaborating on Prætorian's answer I recommend the following:

    for( auto i = strlen(s)-1; i > 0; --i ) {foo(s[i-1];}
    
    • auto because you don't want to care about which type strlen returns. A C++11 compiler (e.g. gcc -std=c++0x, not completely C++11 but auto types work) will do that for you.
    • i = strlen(s) becuase you want to compare to 0 (see below)
    • i > 0 because comparison to 0 is (slightly) faster that comparison to any other number.

    disadvantage is that you have to use i-1 in order to access the string characters.

提交回复
热议问题