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