Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of a C string: std::strlen() vs. std::char_traits<char>::length()

Tags:

c++

Both are equivalent in that they return the length of the null-terminated character sequence. Are there reasons of preferring one to the other?

like image 502
Ruup Avatar asked Mar 22 '23 22:03

Ruup


1 Answers

Use the simpler alternative. std::char_traits::length is great and all, but for C strings it does the same and is much longer code.

Do yourself a favour and avoid code bloat. I’m a huge fan of C++ functions over C equivalent (e.g. I will never use std::strcpy or std::memcpy, there’s a perfectly fine std::copy). But avoiding std::strlen is just silly.

One reason to use C++ functions exclusively is interface uniformity: for instance, both std::strcpy and std::memcpy have atrocious interfaces. However, std::strlen is a perfectly fine algorithm in the best tradition of C++. It doesn’t generalise, true, but the neither do other class-specific free functions found in the standard library.

like image 54
Konrad Rudolph Avatar answered Apr 06 '23 05:04

Konrad Rudolph