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)
The strlen() function calculates the length of a given string. The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (an unsigned integer type). It is defined in the <string. h> header file.
The strlen() function in C is used to calculate the length of a string. Note: strlen() calculates the length of a string up to, but not including, the terminating null character. Return Value: The function returns the length of the string passed to it.
C library function - strlen() The C library function size_t strlen(const char *str) computes the length of the string str up to, but not including the terminating null character.
The syntax of the strlen() function is: strlen(const char* str); Here, str is the string whose length we need to find out, which is casted to a const char* .
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With