Determining the Length of a String Literal

后端 未结 7 1676
栀梦
栀梦 2020-12-16 12:45

Given an array of pointers to string literals:

char *textMessages[] = {
    \"Small text message\",
    \"Slightly larger text message\",
    \"A really larg         


        
相关标签:
7条回答
  • 2020-12-16 13:46

    My suggestion would be to use strlen and turn on compiler optimizations.

    For example, with gcc 4.7 on x86:

    #include <string.h>
    static const char *textMessages[3] = {
        "Small text message",
        "Slightly larger text message",
        "A really large text message that "
        "is spread over multiple lines"
    };
    
    size_t longmessagelen(void)
    {
      return strlen(textMessages[2]);
    }
    

    After running make CFLAGS="-ggdb -O3" example.o:

    $ gdb example.o
    (gdb) disassemble longmessagelen
       0x00000000 <+0>: mov    $0x3e,%eax
       0x00000005 <+5>: ret
    

    I.e. the compiler has replaced the call to strlen with the constant value 0x3e = 62.

    Don't waste time performing optimizations that the compiler can do for you!

    0 讨论(0)
提交回复
热议问题