Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How comparison operator for strings works in C++, if strings are numbers?

Please tell me how less than, greater than operator works for strings if strings are numbers and also have same number of digits. How exactly these operator work ?

For e.g., for the below comparisons-

cout<<("3" > "5")<<endl;
cout<<("31" > "25")<<endl;
cout<<("35" > "35")<<endl;
cout<<("38" > "85")<<endl;
cout<<("53" > "55")<<endl;
cout<<("36" > "35")<<endl;
cout<<("53" > "54")<<endl;

Output I got from CodeBlocks is-

0
0
0
0
0
0
0
like image 285
Frosted Cupcake Avatar asked Dec 20 '17 18:12

Frosted Cupcake


1 Answers

The behaviour of your code is undefined.

The const char[] literals you have entered decay to const char* pointers for the purpose of comparison.

And the behaviour of the comparison operators on pointers is only defined if the pointers are part of the same array; which yours are not.

If you suffix the literals with an s, e.g. "3"s then C++14 onwards will treat that as a std::string and will perform a lexographic comparison.

like image 184
Bathsheba Avatar answered Oct 20 '22 02:10

Bathsheba