cgtkgtkentry

Checking char with if


I really don't know why but that doesn't seem to work. Seems completely valid to me:

gchar *text = gtk_entry_get_text(entry);
if(text == "hello") { 
    //do sth
}
else {
    //do sth else
}

Even when I type hello nothing happens but the code in else { } is called. What is the problem?


Solution

  • In C, string literals are arrays that become pointers in many situations. What you're comparing when you use == are the addresses of the strings (or rather, the addresses of the first characters of each string), not the contents of the string like you are expecting. For example:

    if (text == "hello")
    

    Is sort of like doing:

    if (0x800050a0 == 0x80001000)
    

    It is unlikely that text points to the same location that is storing the characters for "hello".

    To compare string in C, you should use strcmp, which returns an integer based on how the strings compare with each other. If the strings are equal, the function returns 0. If the first string is lexicographically less than the second string, then the function returns -1, otherwise the function returns 1.