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

389 views Asked by At

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]
2

There are 2 answers

8
Bathsheba On BEST ANSWER

'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.)

1
Radoslav Voydanovich On

The operands '1' and '2' are not strings, they're char literals.

The characters represent specific numbers of type char, typically defined by the ASCII table, specifically 49 for '1' and 50 for '2'.

The operator < compares those numbers, and since the number representation of '1' is lesser than that of '2', the result of '1'<'2' is true.