C/C++ Arena

Step 4 of 6

Compare strings correctly

Comparing two strings with == is one of the most common C bugs:

char cmd[20] = "quit";
if (cmd == "quit") { ... }   // wrong: compares addresses

A string in C is an array, and using an array's name gives the address of its first character. So == asks "are these the same place in memory?", not "do they contain the same text?". They're different arrays, so it's false even though the letters match. The compiler warns: result of comparison against a string literal is unspecified.

To compare contents, use strcmp(a, b) from <string.h>. It compares character by character and returns:

#include <stdio.h>
#include <string.h>

int main(void) {
    char answer[20];
    scanf("%19s", answer);
    if (strcmp(answer, "yes") == 0) {
        printf("confirmed\n");
    } else if (strcmp(answer, "no") == 0) {
        printf("cancelled\n");
    } else {
        printf("please answer yes or no\n");
    }
    printf("%d\n", strcmp("apple", "banana") < 0);
    return 0;
}
no
cancelled
1

Read it carefully

strcmp returns 0 for equal, and 0 means false in C. So if (strcmp(a, b)) runs when they're different, the opposite of what it looks like. Always write the comparison out: strcmp(a, b) == 0.

The comparison is exact and case sensitive: "Yes" and "yes" are different, because 'Y' and 'y' have different codes.

Your turn: read a command word. Print planting for plant, defusing for defuse, and unknown command for anything else.

Previous: Write your own strlen Next: Characters are numbers