Is it possible to implement strlen()
in the C preprocessor?
Given:
#define MYSTRING \"bob\"
Is there
Generally the C pre-processor doesn't actually transform any data, it only replaces it. This means that you might be able to perform such an operation provided that you pollute your C pre-processor namespace with data implementing (functional) persistent data structures.
That said, you really don't want to do this as the entire "added" functionality will fail spectacularly once you pass in something other than a string. The C pre-processor has no concept of data type, nor does it have the concept of memory de-referencing (useful if you wanted the length of a string stored in a variable). Basically, it would be a fun "see how far you could take it" exercise, but in the end, you would have a MYSTRING_LEN which would only take you a short distance to the goal.
In addition, the C pre-processor's lack of name spaces means that such a macro expansion system would not be containable. One would have to take care to keep the generated names from interfering with other useful macros. In the end, you would probably run out of memory in the pre-processor for any significant use, as the pre-processor isn't really built to hold a name for each character being converted into the "unit" token, and a name for each "unit" token being compressed into its final decimal notation.
Yes:
#define MYSTRING_LEN(s) strlen(s)
In most compilers, this will produce a compile-time constant for a constant argument ... and you can't do better than that.
In other words: you dont need a macro, just use strlen; the compiler is smart enough to do the work for you.
You can do:
#define MYSTRING sizeof("bob")
That says 4 on my machine, because of the null added to the end.
Of course this only works for a string constant.
Using MSVC 16 (cl.exe -Wall /TC file.c
) this:
#include "stdio.h"
#define LEN_CONST(x) sizeof(x)
int main(void)
{
printf("Size: %d\n", LEN_CONST("Hej mannen"));
return 0;
}
outputs:
Size: 11
The size of the string plus the NUL character.
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()
.