Is it safe to compare const char* with == in C/C++?

314 Views Asked by At

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.

2

There are 2 best solutions below

2
eerorika On BEST ANSWER

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.

1
pmg On

There are 3 situations that can happen

The pointers point to the same space in memory

bar.type = "foobar"; // `bar.type` holds `0xdeadbeef` which holds `"foobar"`
baz.type = "foobar"; // `baz.type` holds `0xdeadbeef` which holds `"foobar"`
if (bar.type == baz.type) { /* true positive */ }

The pointers point to different places in memory, but the memory contents there are the same

bar.type = "foobar"; // `bar.type` holds `0xdeadbeef` which holds `"foobar"`
baz.type = "foobar"; // `baz.type` holds `0xdeadc0ff` which holds `"foobar"`
if (bar.type == baz.type) { /* false negative */ }

The pointers point to different memory areas and those areas have different content

bar.type = "foobar"; // `bar.type` holds `0xdeadbeef` which holds `"foobar"`
baz.type = "bar"; // `baz.type` holds `0xdeadbef2` which holds `"bar"`
if (bar.type == baz.type) { /* true negative */ }

You cannot have a false positive in this situation.