-7

Code 1


#include<stdio.h>    

int main(){
const char st1[]={"Hello"};
const char st2[]={"Hello"};

if(st1==st2){
  printf("True");
}
else{
  printf("False");
}
return 0;
}

Code 2


int main(){
const char *st1="Hello";
const char *st2="Hello";

if(st1==st2){
    printf("True");
}
else{
    printf("False");
}
return 0;
}

Now in first code char array become const. In the first code I got False as optput. And in second code its true. Thank in advance

ChrisF
  • 134,786
  • 31
  • 255
  • 325
ADMIN
  • 19
  • 3

3 Answers3

1

== does not compare the string contents.

In the first snippet st1 are st2 char[6] types with automatic storage duration, and you are allowed to modify the string contents. When using == these types decay to char*. Their addresses must be different, so == will yield false.

In the second snippet, the string literals are read only, in C they are still formally char[6] (cf. C++ where they are const char[6] types) although the behaviour on attempting to modify the contents is undefined. Using const char* types for them is perfectly acceptable and reasonable. Because the contents are read only, the compiler might use the same string and so st1 and st2 might point to the same location in memory. In your case, that is happening, and the result of == is true.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
-1

The second is true because you are using an optimizing compiler. Since str1 and str2 are pointers, it makes them point to the same string, thus saving a little memory.

shawnhcorey
  • 3,545
  • 1
  • 15
  • 17
-2

Totally wrong answer for both C and C++. Pls, vote for delete.

Nikita Smirnov
  • 813
  • 8
  • 17
  • 3
    This is not entirely accurate. In the first snippet, `st1` and `st2` are not pointers, they are arrays. In the second one, they are pointers to `char`, not pointers to arrays. And things they point to most probably are not on the heap. – HolyBlackCat Feb 05 '18 at 13:00
  • C does not have a stack. Please provide a reference to the standard stating otherwise. And HolyBlackCat is right, arrays are not pointers nor vice-vera. – too honest for this site Feb 05 '18 at 13:38
  • And @Olaf is rarely wrong (I've never known them to be) either. This answer is defective. – Bathsheba Feb 05 '18 at 15:03