strlen in the C preprocessor?

前端 未结 4 488
广开言路
广开言路 2020-12-29 02:38

Is it possible to implement strlen() in the C preprocessor?

Given:

#define MYSTRING \"bob\"

Is there

4条回答
  •  既然无缘
    2020-12-29 03:14

    It doesn't use the preprocessor, but sizeof is resolved at compile time. If your string is in an array, you can use that to determine its length at compile time:

    static const char string[] = "bob";
    #define STRLEN(s) (sizeof(s)/sizeof(s[0]))
    

    Keep in mind the fact that STRLEN above will include the null terminator, unlike strlen().

提交回复
热议问题