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 !=
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With