Suppose we have a string
std::string str; // some value is assigned
What is the difference between str.empty()
and str[0] =
string_variable[0]
is required to return the null character if the string is empty. That way there is no undefined behavior and the comparison still works if the string is truly empty. However you could have a string that starts with a null character ("\0Hi there"
) which returns true
even though it is not empty. If you really want to know if it's empty, use empty()
.
The difference is that if the string is empty then string_variable[0]
has undefined behavior; There is no index 0 unless the string is const
-qualified. If the string is const
qualified then it will return a null character.
string_variable.empty()
on the other hand returns true if the string is empty, and false if it is not; the behavior won't be undefined.
empty()
is meant to check whether the string/container is empty or not. It works on all containers that provide it and using empty
clearly states your intent - which means a lot to people reading your code (including you).