Alex Rivera | Logout

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

Asked 2010-10-14T13:27:35.103
20
int main (int argc, **argv)
{
       if (argv[1] == "-hello")
            printf("True\n");
       else
            printf("False\n");
}
# ./myProg -hello
False

Why? I realize strcmp(argv[1], "-hello") == 0 returns true... but why can't I use the equality operator to compare two C strings?

Edit
Report

2 Answers

22

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

answered 2010-10-14T13:30:38.230
2

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.

answered 2010-10-14T13:31:21.397

Your Answer