Question

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?

Was it helpful?

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.

OTHER TIPS

You need to be comparing strings using strcmp:

if(strcmp(text, "hello") == 0) { 
    //do sth
}
else {
    //do sth else
}

What you are doing is comparing two pointers. Read more.

your program compares the pointers of the strings text and "hello". it does not compare the strings character by character.

(other answerers demonstrate means to accomplish character by character comparisons)

Your code compares pointers and they are obviously not equal. You want to compare strings so you probably need to do something like:

if (strcmp(text, "hello") == 0) {
    // Do something
} else {
    // Do something else
}

C strings are not objects and cannot be compared with ==; use strcmp().

You are not comparing the content but the addresses.

To compare the data you should use a strcmp-ish function.

In the comparison

text == "hello"

you're comparing the memory address where your text is stored with the address where the constant string literal "hello" is stored. This is because a C string is really a pointer to an array of chars. It is then interpreted as a sequence of chars until the null-terminator is reached.

Include the library

include <string.h>;

and do comparison as

!strcmp(text, "hello");

The strcmp() function takes two strings and returns 0, if they are equal and nonzero if they are not. If it is nonzero, then negative / positive value determines which one is lexicographically smaller (first / second) and the absolute value determines the first char where they differ.

GLib (#include <glib.h>, you should have it, as you have GTK) has a g_ascii_strcmp() function for this purpose. If your text is non-ascii (which is very likely as it is a user input, which can hold virtually anything), you should compare with g_utf8_collate() instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top