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

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

    Yes. The test doesn't know that ss doesn't get changed inside the loop. If you know that it won't change then I would write:

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

提交回复
热议问题