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

Deepank Gupta
  • 1,597
  • 3
  • 12
  • 11

4 Answers4

6

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
  • 333,147
  • 50
  • 533
  • 760
  • Sorry i am new to C. Where did you find the documentation pasted above? – Jimm Jun 02 '11 at 12:45
  • @Jimm: from a PDF of the C99 standard. You can get a free copy here: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf See this SO answer for information about other standards: http://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents/83763#83763 Note that while it's a good document to have if you're serious about C, it's an absolutely terrible document to *learn* C from. Another book I'd suggest is Harbison & Steele's "C: A Reference Manual". It's not a tutorial either, but it's a great reference and is much more accessible than the standard. – Michael Burr Jun 02 '11 at 18:20
1

If you are comparing strings shouldnt you be using strcmp ?

JonH
  • 32,732
  • 12
  • 87
  • 145
  • @grossvogel - I realize that but I think the op is trying to compare strings. – JonH Aug 03 '10 at 18:17
  • 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 Singhal Aug 03 '10 at 19:25
1

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0

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

zneak
  • 134,922
  • 42
  • 253
  • 328