int main (int argc, **argv)
{
if (argv[1] == \"-hello\")
printf(\"True\\n\");
else
printf(\"False\\n\");
}
Because there is no such thing as a C string.
In C, a string is usually an array of char, or a pointer to char (which is nearly the same). Comparing a pointer/array to a const array won't give the expected results.
UPDATE: what I meant by 'no C string' is, there is no string in C. What's usually referred to as a 'C string' is language independent (as 'Pascal string' is), it's the representation of strings as a null-terminated linear array of characters.
When you're using ==, you're comparing pointers. That is, it will return true if the two operands refer to the same string in memory. Therefore, it's unsuitable for use in comparing strings lexicographically.
In C, string values (including string literals) are represented as arrays of char
followed by a 0 terminator, and you cannot use the ==
operator to compare array contents; the language simply doesn't define the operation.
Except when it is the operand of either the sizeof
or &
operators, or when it is a string literal being used to initialize another array in a declaration, an expression with type "N-element array of T" will have its type implicitly converted (decay) to type "pointer to T", and the value of the expression will be the address of the first element of the array.
So when you write
if (argv[1] == "-hello")
the compiler implicitly converts the expression "-hello"
from type "7-element array of char" to "pointer to char" (argv[1]
is already a pointer type), and the value of the expression is the address of the character '-'
. So what ==
winds up comparing are two pointer values, which are (most likely) never going to be equal since "-hello"
and argv[1]
(most likely) occupy different regions in memory.
This is why you have to use library functions like strcmp()
to compare string values.
In C
because, in most contexts, an array "decays into a pointer to its first element".
So, when you have the array "foobar"
and use it in most contexts, it decays into a pointer:
if (name == "foobar") /* ... */; /* comparing name with a pointer */
What you want it to compare the contents of the array with something. You can do that manually
if ('p' == *("foobar")) /* ... */; /* false: 'p' != 'f' */
if ('m' == *("foobar"+1)) /* ... */; /* false: 'm' != 'o' */
if ('g' == *("foobar"+2)) /* ... */; /* false: 'g' != 'o' */
or automatically
if (strcmp(name, "foobar")) /* name is not "foobar" */;
Because C strings are array of characters. Arrays are simply pointers to the first element in the array, and when you compare two pointers using == it compares the memory address they point to, not the values that they point to.
Because argv[1]
(for instance) is actually a pointer to the string. So all you're doing is comparing pointers.