In the statements like these
cout << ("A" > "A") << endl;
cout << ("a" > "A")<< endl;
cout << ("B" > "a")<< endl;
//...
there are used string literals that have the static storage duration. In C++ string literals have types of constant character arrays. For example the string literal "A"
has type const char[2]
because in memory it is stored like { 'A', '\0' }
.
Execute this statement
std::cout << sizeof( "A" ) << std::endl;
and you will see that the result will be 2.
From the C++ Standard (2.13.5 String literals)
8 Ordinary string literals and UTF-8 string literals are also referred
to as narrow string literals. A narrow string literal has type
“array of n const char”, where n is the size of the string as defined
below, and has static storage duration (3.7).
In expressions like this "A" > "A"
arrays are implicitly converted to pointers to their first characters. So in this expression there are compared two pointers.
From the C++ STandard (4.2 Array-to-pointer conversion)
1 An lvalue or rvalue of type “array of N T” or “array of unknown
bound of T” can be converted to a prvalue of type “pointer to T”. The
temporary materialization conversion (4.4) is applied. The result is
a pointer to the first element of the array.
In general it is not necessary that string literals with equal contents will be stored as one character array. So in fact this expression
"A" == "A"
can yield either true
or false
depending on compiler options that is whether these two string literals stored as one array or as two distinct arrays by the compiler.
It seems your compiler stores equal string literals as one array. In this case this statement
cout << ("A" > "A") << endl;
outputs 0.
Also it seems that the compiler placed the array that stores the string literal "a"
after the array that stores string literal "A"
. So the address of the first character of the string literal "a"
, that is of the character 'a'
, is higher than the address of the first character of the string literal "A"
. So this statement
cout << ("a" > "A")<< endl;
outputs 1.
Also the compiler placed the array that stores the string literal "B"
after the array that stores the string literal "a"
. So again the address of the first character of the string literal "B"
is higher than the address of the first character of the string literal "a"
and in this statement
cout << ("B" > "a")<< endl;
there are compared these addresses. So the statement outputs 1.
And so on.
It seems what you need to do is to compare character literals instead of the string literals. For example
cout << ( 'A' > 'A') << endl;
cout << ('a' > 'A')<< endl;
cout << ('B' > 'a')<< endl;
//...