0

I understand that the code below is outputing the result of a boolean question but i do not understand why it outputs 1 and 0 instead of 1 and 1.

#include <iostream>
using namespace std;

int main() 
{
    string d = "abc", e = "abc";
    char a[] = "abc", b[] = "abc";
    cout << (d == e);
    cout << (a == b);

    return 0;
}
//outputs 10

i also tried outputing the value stored in variables a and b and got the same value for both

#include <iostream>
using namespace std;

int main() 
{
    string d = "abc", e = "abc";
    char a[] = "abc", b[] = "abc";
    cout << (d == e);
    cout << (a == b);
    cout << "\n" << a << "\n";
    cout << b;

    return 0;
}
// outputs 10
//abc
//abc
  • also https://stackoverflow.com/questions/52814457/why-do-only-some-compilers-use-the-same-address-for-identical-string-literals – Pascal Ganaye Jul 26 '20 at 22:09

2 Answers2

1

In C, std::string has a special operator== that actually compares the strings. Contrary to what you might read, std::strings are not equivalent to char arrays. Char arrays are essentially treated as pointers, so == compares the memory addresses, which are different, so the program will output 0.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

For comparing 2 arrays of char you should use strcmp, the == operators compares the pointer addresses instead of the value itself. You can also iterate the arrays and compare element by element.

Diana
  • 140
  • 5