int main (int argc, **argv)
{
if (argv[1] == \"-hello\")
printf(\"True\\n\");
else
printf(\"False\\n\");
}
Because C strings dont exist as such. They are char arrays ending in a \0
.
The equality operator ==
will test that the pointer to the first element of the array are the same. It wont compare lexicographically.
On the other hand "-hello" == "-hello"
may return non zero, but that doesn't mean that the ==
operator compares lexicographycally. That's due to other facts.
If you want to compare lexicographycally, you can always
#define STR_EQ(s1,s2) \
strcmp(s1,s2) == 0
Reading harder I see that you tagged as c++. So you could
std::string arg1 ( argv[1] );
if (arg1 == "-hello"){
// yeahh!!!
}
else{
//awwwww
}
Strings are not native types in C. What you are comparing in that example are two pointers. One to your first argument, and the other is a static character array with the contents of "-hello".
You really want to use strncmp or something similar.
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
The compiler sees a comparison with a char*
on either side, so it does a pointer comparison (which compares the addresses stored in the pointers)