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

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

    Yes, every time you use the loop. Then it will every time calculate the length of the string. so use it like this:

    char str[30];
    for ( int i = 0; str[i] != '\0'; i++)
    {
    //Something;
    }
    

    In the above code str[i] only verifies one particular character in the string at location i each time the loop starts a cycle, thus it will take less memory and is more efficient.

    See this Link for more information.

    In the code below every time the loop runs strlen will count the length of the whole string which is less efficient, takes more time and takes more memory.

    char str[];
    for ( int i = 0; i < strlen(str); i++)
    {
    //Something;
    }
    

提交回复
热议问题