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.