I have a character array and I'm trying to figure out if it matches a string literal, for example:
char value[] = "yes";
if(value == "yes") {
// code block
} else {
// code block
}
This resulted in the following error: comparison with string literal results in unspecified behavior. I also tried something like:
char value[] = "yes";
if(strcmp(value, "yes")) {
// code block
} else {
// code block
}
This didn't yield any compiler errors but it is not behaving as expected.
Check the documentation for strcmp. Hint: it doesn't return a boolean value.
ETA:
==
doesn't work in general becausecstr1 == cstr2
compares pointers, so that comparison will only be true ifcstr1
andcstr2
point to the same memory location, even if they happen to both refer to strings that are lexicographically equal. What you tried (comparing a cstring to a literal, e.g.cstr == "yes"
) especially won't work, because the standard doesn't require it to. In a reasonable implementation I doubt it would explode, butcstr == "yes"
is unlikely to ever succeed, becausecstr
is unlikely to refer to the address that the string constant"yes"
lives in.std::strcmp
returns 0 if strings are equal.strcmp returns a tri-state value to indicate what the relative order of the two strings are. When making a call like strcmp(a, b), the function returns