views:

858

answers:

3

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 behaviour. 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.

+14  A: 

strcmp returns 0 if strings are equal.

PiotrLegnica
+15  A: 

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.

David Seiler
+1: The only one who bothered to explain *why* the OP's first attempt didn't work! Much more important than explaining something that could be found in 10 seconds by reading the strcmp man page (or googling it), in my book.
Jefromi
Not "unlikely". In the above code, `value` cannot have the same address as the string literal in any conforming implementation. When the warning mentions unspecified behaviour, I assume it means that it's unspecified whether the same literal used in different places ends up with the same address, or not.
Steve Jessop
@onebyone: really? I thought conforming implementations were permitted to coalesce string literals, so that if you had char* s = "yes";, s == "yes" could then potentially be true.
David Seiler
Sure, that's the bit that is unspecified - it's up to the implementation whether it's true or false. But in the code in the question, `value` is an array, not a pointer. So there's no way that its first byte can legally have the same address as the first byte of any literal, or for that matter any other object. That's why when it degrades to a pointer for comparison with "yes", it isn't "unlikely" to be equal, it's never equal.
Steve Jessop
Oh, I see what you mean. Yes, what the OP did can't ever work.
David Seiler
+3  A: 

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
R Samuel Klatchko