Evaluating strlen at compilation time?

◇◆丶佛笑我妖孽 提交于 2019-11-27 07:05:55

问题


If my code has this constexpr string

constexpr char my_str[] = "hello";

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

What about strlen(my_str)? Can/should it also be evaluated to 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? Surely not "maybe"?


回答1:


21.8, 1 and 2, in the standard says:

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

  2. The contents of these headers shall be the same as the Standard C Library headers <ctype.h>, <wctype.h>, <string.h>, <wchar.h>, and <stdlib.h> and the C Unicode TR header <uchar.h>, respectively, with the following modifications:

strlen is defined in in <cstring> in c++. The modifications that follow do not mention strlen. From that, I would conclude that the signature in C++ must be exactly the same as it is in C, and since C does not have constexpr, it is technically non-compliant. That said, this is one of those non-compliant things that's unlikely to do any harm, beyond relying on it on one platform and then not finding it on another.




回答2:


In C++17 you can use std::char_traits::length, which is constexpr, instead of strlen.




回答3:


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.



来源:https://stackoverflow.com/questions/46101386/evaluating-strlen-at-compilation-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!