using namespace std; int ma" /> using namespace std; int ma" /> using namespace std; int ma"/>

Why compare operator <,>,= given wrong output when comparing strings?

120 Views Asked by At

I am comparing two string using comparison operators(<,>,=).

The output of "a" < "b" In this case is 0.

#include<iostream>
using namespace std;
int main()
{
    cout<<("a" < "a")<<endl;
    cout<<("b" < "a")<<endl;
    cout<<("a" < "b")<<endl;

    return 0;
}

outputs -

0
1
0

But why the output is changing when i am comparing only "a" < "b" ?

#include<iostream>
using namespace std;
int main()
{
    // cout<<("a" < "a")<<endl;
    // cout<<("b" < "a")<<endl;
    cout<<("a" < "b")<<endl;

    return 0;
}

output - 1

Here are the SS-

[1st output]https://i.stack.imgur.com/rHqzM.png

[2nd output]https://i.stack.imgur.com/IrUEx.png

I have so confused right now !! pls anyone can assist me with this

1

There are 1 best solutions below

2
bitmask On

You are not comparing std::string objects with well defined inequality operations. You are comparing string literals with unspecified memory locations. Therefore < will not return what you expect:

The type of an unprefixed string literal is const char[N], where N is the size of the string [..], including the null terminator.