As the question is tagged with c++, in addition to David Seilers excellent explanation on why strcmp()
did not work in your case, I want to point out, that strcmp()
does not work on character arrays in general, only on null-terminated character arrays (Source).
In your case, you are assigning a string literal to a character array, which will result in a null-terminated character array automatically, so no problem here. But, if you slice your character array out of e. g. a buffer, it may not be null-terminated. In such cases, it is dangerous to use strcmp()
as it will traverse the memory until it finds a null byte ('\0'
) to form a string.
Another solution to your problem would be (using C++ std::string
):
char value[] = "yes";
if (std::string{value} == "yes")) {
// code block
} else {
// code block
}
This will also only work for null-terminated character arrays. If your character array is not null-terminated, tell the std::string
constructor how long your character array is:
char value[3] = "yes";
if (std::string{value, 3} == "yes")) {
// code block
} else {
// code block
}