1

I am creating a server/client socket program and am in the process of making a method to print server input.

Here's my code:

void *admin_handler (void *ptr) {
    char strBuf [100000];
    const char strExit [20] = "Server: terminated.";

    while(1) {
        scanf ("%s", strBuf);
        int i;
        for (i=0; i < nClient; i++){
            if (strBuf == "Exit"){
                write (nFDList [i], strExit, strlen (strExit) + 1);
            }
            else {
                write (nFDList [i], strBuf, strlen (strBuf) + 1);
            }
        }
    };
}

When I execute, though, even when I type in "Exit", it still executes the else statement. How can I modify the if statement to execute when I type "Exit"?

melpomene
  • 84,125
  • 8
  • 85
  • 148
Andrew
  • 45
  • 9

1 Answers1

2

The best way to compare strings in C is using strcmp() (or strncmp() if one is interested in safety with unknown strings).

The equality operator == compares the operands directly, after they "decay" to pointers; the pointers do not change and are of course different. strcmp(), by contrast, inspects the contents of the memory pointed to, which may be equal.

As an aside, the same issue exists in Java: == checks whether both sides are the same objects, similar to the C equivalent, while .equals() inspects the object contents, similar to strcmp().

C#, by contrast, overloaded == for strings so that it would indeed look at the contents, which makes a lot of sense for a language where operator overloading is possible (which C is not): Testing the identity of the objects is almost never desired and, as we see, is a common source of error.

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
Daniel PC
  • 46
  • 4
  • Sorry, I kind of hijacked your answer ;-). I only wanted to provide some context and got carried away. But it is useful information, even if it is redundant on SO. – Peter - Reinstate Monica Apr 30 '18 at 06:15