Using the equality operator == to compare two strings for equality in C [duplicate]

Solution 1:

Because argv[1] (for instance) is actually a pointer to the string. So all you're doing is comparing pointers.

Solution 2:

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)

Solution 3:

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" */;