how many times will strlen() be called in this for loop?

后端 未结 6 727
渐次进展
渐次进展 2020-12-03 14:46

Will the strlen() function below get called just once (with the value stored for further comparisons); or is it going to be called every time the comparison is performed?

6条回答
  •  执念已碎
    2020-12-03 15:05

    The number of times strlen(word) is executed depends on:

    1. If word is declared as constant (the data is constant)
    2. Or the compiler can detect that word is not changed.

    Take the following example:

    char word[256] = "Grow";
    
    for (i = 0; i < strlen(word); ++i)
    {
      strcat(word, "*");
    }
    

    In this example, the variable word is modified withing the loop:
    0) "Grow" -- length == 4
    1) "Grow*" -- length == 5
    2) "Grow**" -- length == 6

    However, the compiler can factor out the strlen call, so it is called once, if the variable word is declared as constant:

    void my_function(const char * word)
    {
      for (i = 0; i < strlen(word); ++i)
      {
         printf("%d) %s\n", i, word);
      }
      return;
    }
    

    The function has declared that the variable word is constant data (actually, a pointer to constant data). Thus the length won't change, so the compiler can only call strlen once.

    When in doubt, you can always perform the optimization yourself, which may present more readable code in this case.

提交回复
热议问题