-2

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.sstatic.net/rHqzM.png

[2nd output]https://i.sstatic.net/IrUEx.png

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

7
  • 1
    you are not comparing strings, you are comparing arrays which decay to pointers Commented Jun 20, 2023 at 12:03
  • 2
    strings in c++ are std::string. std::string("a") < std::string("b") you want Commented Jun 20, 2023 at 12:03
  • do not ignore compiler warnings ! godbolt.org/z/qjWx6Mx84 ! Commented Jun 20, 2023 at 12:05
  • @463035818_is_not_an_ai C-style strings remain part of C++. In fact arguably more so than std::string which is part of the library, while support for literal string constants as in this example is built-in. Commented Jun 20, 2023 at 12:18
  • In an expression a literal string constant has type const char* - you are comparing pointers, not strings. C-style strings are not data types. Use std::strcmp() or the std::string class for which these operators have overloads. Commented Jun 20, 2023 at 12:22

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah ... the meaning of comparing string literals has well-defined inequality operations. It is comparing the address of the first character of each (statically allocated) string literal. The result of the comparison is unspecified (since the layout in memory is unspecified).
@Peter Yep, as I say, the memory location is unspecified. Therefore the result is not what OP was expecting.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.