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

后端 未结 18 1703
再見小時候
再見小時候 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:10

    Yes. strlen will be calculated everytime when i increases.

    If you didn't change ss with in the loop means it won't affect logic otherwise it will affect.

    It is safer to use following code.

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

提交回复
热议问题