The string literal "abc"
includes a null terminator byte. The declaration of a
is the same as if it were
char a[] = { 'a', 'b', 'c', '\0' };
If you want not to count the termination, or characters following it, you could use std::strlen
. However, this relies on the existence of that byte and it could crash when given b
. You could make an overload set:
template< typename t >
std::size_t string_length( t const & s ) {
return s.size();
}
std::size_t string_length( char const * s ) { // requires a termination byte!
return std::strlen( s );
}
template< std::size_t n > // requires the name of the array to be passed!
std::size_t string_length( char const (&s)[n] ) {
return std::find( &* s, s + n, '\0' ) - s;
}
This is however a very dangerous practice because if you assign the b
array to a char *
variable, that variable will select the second overload, but the terminator byte is missing.