Home > Mobile >  How to strlen in constexpr?
How to strlen in constexpr?

Time:03-27

I'm using clang 13.0.1
The code below works but it's obviously ugly. How do I write a strlen? -Edit- Inspired by the answer, it seems like I can just implement strlen myself

#include <cstdio>
constexpr int test(const char*sz) {
    if (sz[0] == 0)
        return 0;
    if (sz[1] == 0)
        return 1;
    if (sz[2] == 0)
        return 2;
    return -1;
    //return strlen(sz);
}
constinit int c = test("Hi");

int main() {
    printf("C %d\n", c);
}

CodePudding user response:

You can just use C 17 string_view and get the length of the raw string through the member function size()

#include <string_view>
constexpr int test(std::string_view sz) {
  return sz.size();
}

Demo

Another way is to use std::char_traits::length which is constexpr in C 17

#include <string>
constexpr int test(const char* sz) {
  return std::char_traits<char>::length(sz);
}
  • Related