Why string literal comparison is implementation defined behavior in C++?

98 views Asked by At

I have read following in The C++ Programming Language special 3rd edition that:

Whether two identical character literals are allocated as one is implementation defined (§C.1).

const char* p="Heraclitus";
const char* q="Heraclitus";

void g ()
{
       if (p == q ) cout << "one!\n"; // result is implementation defined
       // ...
}

Note that == compares addresses (pointer values) when applied to pointers, and not the values pointed to.

I have tried following program on gcc 4.8.1 & MSVS 2010

#include <iostream>
int main()
{
    const char* p="Heraclitus";
    const char* q="Heraclitus";
    if(p==q)
        std::cout<<"fine!!!";
    else
        std::cout<<"!fine";
}

Output:

fine!!! (on gcc 4.8.1)

!fine (on MSVS 2010)

Why this is left as implementation defined behavior? What is the reason?

1

There are 1 answers

0
Shafik Yaghmour On BEST ANSWER

We can find a rationale in this comp.std.c thread: History question: String literals and it says:

GCC might have served as an example but not as motivation. Partly the desire to have string literals in ROMmable data was to support, er, ROMming. I vaguely recall having used a couple of C implementations (before the X3J11 decision was made) where string literals were either automatically pooled or stored in a constant data program section. Given the existing variety of practice and the availability of an easy work-around when the original UNIX properties were wanted, it seemed best to not try to guarantee uniqueness and writability of string literals.