Search code examples
cstringcomparison-operators

If Else falls with variable in C


I'm a C beginner, I don't understand why this code is not working?

void main(){
    char userInput = "a";

    if(userInput == "a"){
        printf("a");
    } else printf("b");

    getch();
}

returning "b"

but this one is working

void main(){
    char userInput;

    if("a" == "a"){
        printf("a");
    } else printf("b");

    getch();
}

returning "a"

What is the difference?


Solution

  • A literal represented like "a", is a string literal. The essential type is an array of chars, like char [size]. It is not a compatible type with char, so the assignment

    char userInput = "a";
    

    is not valid.

    You want to use a character constant, you write something like

    char userInput = 'a';
    

    That said, if("a" == "a") seems to work in your case, but it does not do what you think it does. It does not compare the content, rather, it compares the base address (address of the first element) of the strings, and in your case, they seem to be the same. Your compiler, happens to use the same memory location for the identical string literals (optimization) - so you see a truthy result, but this is not guaranteed by the standard. A(ny) compiler is free to choose it's own memory allocation strategy, with or without optimization process.

    Using gcc, if the -fno-merge-constants is used as compilation option, this condition is expected to evaluate to falsy.