Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to strlen in constexpr?

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);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading