Evaluating strlen at compilation time?

前端 未结 3 2038
面向向阳花
面向向阳花 2020-12-11 04:22

If my code has this constexpr string

constexpr char my_str[] = \"hello\";

the type of my_str contains information

3条回答
  •  独厮守ぢ
    2020-12-11 05:15

    Firstly, you might be confusing the functionality of the two: strlen() gives the length of the whole string and sizeof() gives the size of memory space occupied by the data type in memory.

    The function sizeof() is a compile-time expression because the memory to your variable is allocated during compile-time(given its not dynamically written). Thus, giving you the size of memory occupied by the data type. It doesn't care about the value of the variable, just cares about memory space.

    Whereas, strlen() is a function that takes a pointer to a character, and keeps incrementing the memory from this character o, looking for a NULL character, which is at the end of the string. It counts the number of characters before it finds the NULL character.Basically, giving you the length.

提交回复
热议问题