Estimating strlen at compile time?

If my code has this string constexpr

 constexpr char my_str[] = "hello"; 

type my_str contains information about its size, i.e. sizeof(my_str) is a constant of 6 and can be used wherever a constant is required.

What about strlen(my_str) ? Can / should also be evaluated with a compile-time constant?

Here is an example for yes: https://ideone.com/2U65bN

Here is an example for no: http://coliru.stacked-crooked.com/a/8cb094776dfc5969

What does the Standard say about this? Certainly not "maybe"?

+2
source share
2 answers

21.8, 1 and 2, the standard says:

  • Tables 74, 75, 76, 77, 78, and 79 describe the headers <cctype> , <cwctype> , <cstring> , <cwchar> , <cstdlib> (character conversions), and <cuchar> respectively.

  • The contents of these headers must match the headers of the standard library C <ctype.h> , <wctype.h> , <string.h> , <wchar.h> and <stdlib.h> , and the header is TR Unicode TR <uchar.h> , accordingly, with the following changes:

strlen defined in <cstring> in C ++. Subsequent modifications do not mention strlen . From this, I would conclude that the signature in C ++ should be exactly the same as in C, and since C does not have constexpr , it is technically incompatible. However, this is one of those incompatible things that are unlikely to do any harm without relying on it on one platform, and then not finding it on another.

+1
source

First, you can confuse the functionality of two: strlen () sets the length of the entire string, and sizeof () sets the size of the memory space occupied by the data type in memory.

The sizeof() function is a compile-time expression because the memory for your variable is allocated at compile time (given its dynamic writing). Thus, you get the size of the memory occupied by the data type. He does not care about the value of the variable, he just cares about the memory space.

Whereas strlen() is a function that takes a pointer to a character and continues to increase the memory from that character o, looking for the NULL character that is at the end of the line. It counts the number of characters before it finds a NULL character. Mostly indicating length.

+1
source

Source: https://habr.com/ru/post/1271615/


All Articles