Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strlen in the C preprocessor?

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) 
like image 418
Joby Taffey Avatar asked Feb 16 '11 21:02

Joby Taffey


People also ask

What is strlen () in C?

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.

Can we use strlen in C?

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.

What library is strlen in C?

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.

What is the syntax of strlen ()?

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* .


1 Answers

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

like image 173
nmichaels Avatar answered Sep 29 '22 08:09

nmichaels