Search code examples
c++comparisonstring-comparisonliteralscharacter-literals

How do C++ compiler interpret comparison logic in string/character?


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]

Solution

  • '1' is a char type in C++ with an implementation defined value - although the ASCII value of the character 1 is 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' is true on any platform. The same cannot be said for 'a' < 'b' always being true although I've never come across a platform where it is not true. 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 both const char[3] constants decay to const 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 all int types.)