Let's say I have a struct that keeps track of a type using a const char*
:
struct Foo {
const char* type;
}
Suppose I only ever assign this value using a string literal throughout my program:
Foo bar;
bar.type = "TypeA";
Foo baz;
baz.type = "TypeB";
Is it safe to compare this value using a regular ==
as opposed to a strcmp
?
if (bar.type == baz.type) {
printf("Same\n");
} else {
printf("Different\n");
}
I would like to do this for performance reasons.
Is it safe to compare this value using a regular == as opposed to a strcmp?
No. It isn't safe in the sense that two string literals - even with same content - are not guaranteed to have the same storage address, and thus may compare different.
You can compare the address initially and only compare content if the address differs. You can return early if the address matches.