strcmp()
has undefined behaviour if either argument is a null pointer. Therefore it is necessary to check for null before calling strcmp()
.
For example, to only call strcmp()
if both intended arguments are not null
if (first && second && !strcmp(first, second))
{
// first and second are both non-null, and contain matching strings
}
or (more verbosely, C++11 and later)
if (first != nullptr && second != nullptr && strcmp(first, second) == 0)
{
// first and second are both non-null, and contain matching strings
}
In C++, you'd be better off using the std::string
type, rather than messing around with arrays of char
, string termination, and functions like strcmp()
.