Reputation: 177
Both are equivalent in that they return the length of the null-terminated character sequence. Are there reasons of preferring one to the other?
Upvotes: 4
Views: 3970
Reputation: 604
Since C++17, std::char_traits<char>::length()
is constexpr
meaning it should be computed at compilation time if possible (i.e. if the parameter is constant).
In practice, modern compiler already optimize strlen
to compute string length at compilation too for constexpr
expressions, even though it's not really standard.
That being said, I agree strlen
is more readable.
Upvotes: 1
Reputation: 177
Both Zack Howland and Konrad Rudolph have a point. Thanks. I accept both answers. The summarized reply would be: There doesn't seem to be any except personal preference either for shorter code or the C++ standard library (I leave out generalization since it wasn't the point of the question as can be seen from the title).
Upvotes: 0
Reputation: 545518
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.
Upvotes: 6
Reputation: 15872
std::strlen()
is a holdover from the C Standard Library and only operates on a const char*
(it is unsafe in that it has undefined behavior if the string is not null terminated). If the string is using a wide character set (e.g. const unsigned short*
), std::strlen()
is useless.
std::char_traits<T>::length()
will operate on whatever the T
type is (e.g. if it is an unsigned short
, it will still operate properly, but also requires a null terminated value - that is the last value must be T(0)
- if an array of T
's passed to it is not null terminated, behavior is undefined as well).
In general, when dealing with strings, it is better to use std::string::length()
instead of using C-style character strings.
Upvotes: 3
Reputation: 5711
std::strlen()
is a C standard library compatibility (even though it is part of ISO C++) function that takes const char*
as an argument. length()
is a method of the std::string
family of classes. So if you want to use strlen()
on std::string
you'd have to write:
strlen(mystring.c_str())
which is less tidy than mystr.length()
. Apart from that, there should be no tangible difference (for char
type, that is).
Upvotes: -2