Reputation: 1637
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.
Upvotes: 1
Views: 161
Reputation: 320531
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.
Upvotes: 1
Reputation: 340218
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]
).
Upvotes: 6
Reputation: 138051
Don't rely on it. This depends on an omptimization the compiler does to reduce the size of the binary.
Upvotes: 0