Search code examples
cstringoptimizationstrlen

Is strlen of a const char* optimised?


Can I use strlen of a const char* in a loop like this and expect O(n) time complexity, or would it result in O(n^2)? I think it looks cleaner than using a variable for the string length.

void send_str( const char* data ) {
    for (uint8_t i = 0; i < strlen(data); i++)
        send_byte( data[i] );
}

Does it depend on the optimization level?


Solution

  • I don't think you can ever depend on an optimization happening.

    Why not do it like this, if you really want to avoid an extra variable:

    void send_str(const char *data)
    {
      for(size_t i = strlen(data); i != 0; --i)
        send_byte(*data++);
    }
    

    Or, less silly, and more like an actual production-quality C program:

    void send_str(const char *data)
    {
      while(*data != '\0')
        send_byte(*data++);
    }
    

    There's no point at all in iterating over the characters twice, so don't call strlen() at all, detect the end-of-string yourself.