When we compare numbers in a string/character format, how does the c++ compiler interpret it? The example below will make it clear.
#include <iostream>
using namespace std;
int main() {
// your code goes here
if ('1'<'2')
cout<<"true";
return 0;
}
The output is
true
What is happening inside the compiler? Is there an implicit conversion happening from string to integer just like when we refer an index in an array using a character,
arr['a']
=> arr[97]
'1'is achartype in C++ with an implementation defined value - although the ASCII value of the character1is common, and it cannot be negative.The expression
arr['a']is defined as per pointer arithmetic:*(arr + 'a'). If this is outside the bounds of the array then the behaviour of the program is undefined.Note that
'1' < '2'istrueon any platform. The same cannot be said for'a' < 'b'always beingtruealthough I've never come across a platform where it is nottrue. That said, in ASCII'A'is less than'a', but in EBCDIC (in all variants)'A'is greater than'a'!The behaviour of an expression like
"ab" < "cd"is unspecified. This is because bothconst char[3]constants decay toconst char*types, and the behaviour of comparing two pointers that do not point to objects in the same array is unspecified.(A final note: in C
'1','2', and'a'are allinttypes.)