cstringcs50

error: result of comparison against a string literal is unspecified for C


So I am trying to create a little joke with C and I don´t know what I am doing wrong. I see the Error "error: result of comparison against a string literal is unspecified" and do not know how to fix it, can someone help.

#include<stdio.h>
#include<cs50.h>
int main(void){
    string a = get_string("ENTER YOUR NAME FOR READING\n");
    if (a == "david")
    ;
    {
        printf("...");
    }
}

Solution

  • Your code has three issues:

    ###1.

    if (a == "david")

    a decays to a pointer to the first element of array a.

    "david" is a string literal.

    With the if Statement, you attempt to compare the address of the array a by the address of the string literal "david". String comparison does not work that way in C.

    Use strcmp() - header string.h to compare strings.

    strcmp() returns 0 if the strings are equal. To make the if condition turn true you need to use ! negation operator.

    ###2.

    There is a misplaced ; between the if condition and if body. Remove it.

    ###3. The use of cs50.h is deprecated. If you are not required to use it explicitly, leave your hands off from it.


    #include <stdio.h>
    #include <string.h>
    
    int main (void) {
        char a[20];
    
        printf("ENTER YOUR NAME FOR READING:\n");
      
        if (!fgets(a, sizeof a, stdin))
        {
             fputs("Failure at input", stderr);
             // further Error routine.
        }
    
        a[strcspn(a, "\n")] = 0;
        
        if (!strcmp(a,"david"))
        {
            printf("...");
        }
    }