strlen in the C preprocessor?

Joby Taffey picture Joby Taffey · Feb 16, 2011 · Viewed 24.2k times · Source

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

Given:

#define MYSTRING "bob"

Is there some preprocessor macro, X, which would let me say:

#define MYSTRING_LEN X(MYSTRING)

Answer

nmichaels picture nmichaels · Feb 16, 2011

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().