tags:

views:

82

answers:

4
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.

A: 

Don't rely on it. This depends on an omptimization the compiler does to reduce the size of the binary.

zneak
+6  A: 

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]).

Michael Burr
+1  A: 

If you are comparing strings shouldnt you be using strcmp ?

JonH
It's the pointers that are being compared.
grossvogel
@grossvogel - I realize that but I think the op is trying to compare strings.
JonH
@JonH: if the OP is trying to compare strings, he wouldn't ask the question: `strcmp("abc", "abc")` should equal 0 and I doubt that that's what the OP is asking.
Alok
No I am just being curious...
Deepank Gupta
+1  A: 

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.

AndreyT