char *p = "abc";
char *q = "abc";
if (p == q)
printf ("equal");
else
printf ("not equal");
Output: equal
Is it compiler specific, or is it defined somewhere in the standards to be as expected behaviour.
char *p = "abc";
char *q = "abc";
if (p == q)
printf ("equal");
else
printf ("not equal");
Output: equal
Is it compiler specific, or is it defined somewhere in the standards to be as expected behaviour.
The compiler is permitted to 'coalesce' string literals, but is not required to.
From 6.4.5/6 String literals:
It is unspecified whether these arrays are distinct provided their elements have the appropriate values.
In fact, the compiler could merge the following set of literals:
char* p = "abcdef";
char* q = "def";
such that q
might point 'inside' the string pointed to by p
(ie., q == &p[3]
).
If you are comparing strings shouldnt you be using strcmp ?
It is not about some "data allocation to pointers". It is about whether each instance of string literal is guaranteed to be a different/distinct array object in C. The answer is no, they are not guaranteed to be distinct. The behavior in this case is implementation-dependent. You can get identical pointers in your example, or you can get different pointers.
Don't rely on it. This depends on an omptimization the compiler does to reduce the size of the binary.