Search code examples
cstringstring-comparison

strcmp and double equal relational operator not working in C


using the following program in C, the string comparison is not working:

#include<stdio.h>
#include<string.h>
int main(){
    char ch[]="ABC";
    printf("%d \n", strlen(ch));    // output 3
    printf("%d \n", strlen("ABC")); // output 3
    if(strcmp("ABC",ch)){
        printf("\n Matched");
    }else{
        printf("\n Not matched"); // this will be output
    }

    if("ABC" == ch){
        printf("\n Matched");
    }else{
        printf("\n Not matched"); // this will be output
    }
}//ends main

the output is:

3

3

 Not matched

 Not matched

Why the string is not matching?


Solution

  • With "ABC" == ch you compare two pointers, you don't compare what the pointers are pointing to. And these two pointers will never be equal.

    And the strcmp function returns zero if the strings are equal. Zero is considered "false" in C, and all non-zero values are "true".


    String literals in C are really arrays of (read-only) characters, including the terminator. As all arrays they decay to pointers to their first elements when they are used in most expressions.