You compared addresses. String literal which is an array of characters decays into pointer to the first element here. You compared them which was certainly not your intention. Use strcmp
instead (or similar functions like strncmp
).
if( strcmp(argv[1],"fizzbuzz") == 0 ){
...
}
My claim that string literal is an array of char
is from standard §6.4.5¶6 C11 standard N1570
In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.78) The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence.
And also this decaying §6.3.2.1¶3 C11 standard N1570
Except when it is the operand of the sizeof operator, the _Alignof
operator, or the unary &
operator, or is a string literal used to initialize an array, an expression that has type 'array of type' is converted to an expression with type 'pointer to type' that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
Also as they are different object it is clearly the case that they will not be same as a result the if
statement condition evaluates to false irrsepective of what you pass as the argument to the main
function.
Using strcmp
- you are basically containing the content of the array with the passed argument until \0
is found. This is clearly what you want to do when you want to compare strings.
Remember There's no undefined behaviour in comparing pointers to unrelated objects for equality or inequality. But if you check 6.5.3p5 you will see
Comparing pointers with >
, >=
or <
or <=
and then if the pointers are not pointing to the same object the behavior is undefined.