Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two string literals have the same pointer value?

When I run this program using MinGW, im getting output as "="

#include<iostream>

using namespace std;

int main()
{
 char *str1 = "Hello";
 char *str2 = "Hello";

 if(str1==str2)
 cout<<"=";
 else
 cout<<"!=";


 return 0;
}

However, logically, it should be !=, coz these are pointers and they are pointing to different memory locations. When I run this code in my Turbo C++, i get !=

like image 334
Vipul bhojwani Avatar asked Nov 22 '12 15:11

Vipul bhojwani


2 Answers

You are right in that they are pointers. However, whether they are pointing to different locations or not depends on the implementation. It is perfectly valid for a compiler to store a string literal just once and use its address wherever it's used in code.

like image 153
Angew is no longer proud of SO Avatar answered Oct 07 '22 05:10

Angew is no longer proud of SO


There are no guarantees that the two pointers are pointing to different memory locations. Maybe it is because optimizations, or the compiler uses its own rules... the behavior is "Implementation Defined".

According to the standard (C++11 §2.14.5 String Literals):

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined.

like image 23
timothyqiu Avatar answered Oct 07 '22 05:10

timothyqiu