Home > Enterprise >  Can someone explain to me why txt3, txt4 and txt4, txt5 are not equal?
Can someone explain to me why txt3, txt4 and txt4, txt5 are not equal?

Time:03-08

Can someone explain to me why txt3, txt4 and txt4, txt5 are not equal?

Why does (txt3 == txt4) and (txt5 == txt6) give false?

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string txt1("EL020GM");
  string txt2("EL020GM");

  char txt3[] = "EL020GM";
  char txt4[] = "EL020GM";

  char * txt5 = &txt3[0];
  char * txt6 = &txt4[0];

  const char * txt7 = "EL020GM";
  const char * txt8 = "EL020GM";

  if(txt1 == txt2)  { std::cout << "yes\n";  }  else{ std::cout << "no\n"; }
  if(txt3 == txt4)  { std::cout << "yes\n";  }  else{ std::cout << "no\n"; }
  if(txt5 == txt6)  { std::cout << "yes\n";  }  else{ std::cout << "no\n"; }
  if(txt7 == txt8)  { std::cout << "yes\n";  }  else{ std::cout << "no\n"; }

  return 0; 
}

CodePudding user response:

Because you can't use == to compare C-style strings. You have to use strcmp():

if (strcmp(txt1, txt2) == 0) ...

That's how you do a string comparison of C-style strings.

Or better yet, use C strings.

What your code is doing is asking if the POINTERS are pointing to the same place. They don't. You are not comparing the data being pointed at.

CodePudding user response:

Below are C strings (an array of characters)

char txt3[] = "EL020GM";
char txt4[] = "EL020GM";

means txt3 is a located at some address and is holding the group of characters "EL020GM" and txt4 is located at some other address and is holding the group of characters "EL020GM".

Assume that txt3 is located at address 1000, E is stored in address 1000, L is at 1001 ...

Same way assume txt4 is located at address 2000, E is stored in address 2000, L is at 2001 ...

txt3 == txt4 

This means you are asking if both addresses are same. They are not. So it will return false.

Now,

char * txt5 = &txt3[0];
char * txt6 = &txt4[0];

txt5 contains the address of first character in txt3 which is 1000 (assume txt3 is located at address 1000 and txt4 located at 2000). txt6 contains the address of first character in txt4 which is 2000.

txt5 == txt6

means you are asking whether the addresses of first characters in txt3, txt4 are same. They are not. So it is also returning false.

If you want to compare c strings, you need to use strcmp().

C strings are different.

string txt1("EL020GM");
string txt2("EL020GM");

C strings are of type 'string' class. This class internally maintains a buffer to hold the string and the class also overloads "==" operator.

When you compare C strings, the overloaded "==" operator function will be invoked and the function will compare the characters (one by one) stored in the buffers of the string objects and returns true if all characters are same, else it will return false.

  •  Tags:  
  • c
  • Related