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

后端 未结 6 704
渐次进展
渐次进展 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:03

    It will be evaluated for every iteration of the loop (edit: if necessary).

    Like Tatu said, if word isn't going to change in length, you could do the strlen call before the for loop. But as Chris said, the compiler may be good enough to realize that word can't change, and eliminate the duplicate calls itself.

    But if word can change in length during the loop, then of course you'll need to keep the strlen call in the loop condition.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 15:10

    I'll sometimes code that as ...

    for (int i = 0, n = strlen(word); i < n; ++i) { /* do stuff */ }
    

    ... so that strlen is only called once (to improve performance).

    0 讨论(0)
  • 2020-12-03 15:11

    strlen checks the lenght of the provided string. Which means that if the lenght is 10. Your iteration will keep on going as long as i is below 10.

    And in that case. 10 times.

    Read more about loops

    0 讨论(0)
  • 2020-12-03 15:24

    That's implementation-dependent. Usually, it gets called every time, but, if the compiler can see that word never changes, and that strlen is a pure function (no side effects), it can lift the call.

    See: http://underhanded.xcott.com/?page_id=15 for a well-known example of this being exploited. :-)

    0 讨论(0)
  • 2020-12-03 15:25

    It will be called for each iteration. The following code only calls strlen function once.

    for (i = 0, j = strlen(word); i < j i++)
    { /* do stuff */ }
    
    0 讨论(0)
提交回复
热议问题