The ==
operator, as well as the relations comparison operators <
, <=
, >
and >=
, when applied to pointer types, compares the pointer values, not the objects pointed to.
Hence a == b
will evaluate to 1
if and only if a
and b
point to the same object.
In your example, Text
and n.data
are initialized with two identical string literals "hello"
. It is implementation defined whether these string literals are compiled as 2 different objects or as a single object.
On your system, the compiler generates the same object, so both pointers point to the same object and thus are identical.
Try this code to verify that ==
is inappropriate to compare strings:
#include <stdio.h>
#include <string.h>
typedef struct S {
const char *data;
} S;
int main(void) {
char copy[] = "hello";
const char *Text = "hello";
S n = { "hello" };
printf("pointer comparison: %d, string comparison: %d\n",
n.data == Text, strcmp(n.data, Text) == 0);
printf("pointer comparison: %d, string comparison: %d\n",
n.data == copy, strcmp(n.data, copy) == 0);
return 0;
}
Output:
pointer comparison: 1, string comparison: 1
pointer comparison: 0, string comparison: 1