Comparing character arrays and string literals in C++
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 because cstr1 == cstr2
compares pointers, so that comparison will only be true if cstr1
and cstr2
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, but cstr == "yes"
is unlikely to ever succeed, because cstr
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
- a value < 0 when a < b
- 0 when a == b
- a value > 0 when a > b
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
}
精彩评论