1
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a;
    char b;
    a = 66000; 
    b = 'C';
    if (b == a)
    std::cout << "1";
    else
    std::cout << "2";     
}

The output of the above function is

2

What I don't understand is:

  • How can C++ compare two different datatypes? I searched on google, I didn't find a satisfying answer.
  • Is this a compiler issue or something I failed to read?
  • Are b == a and a == b the same comparison? Does order matter?

When a's value is 67, the above program gives "1" as output.

kvk30
  • 1,133
  • 1
  • 13
  • 33
  • 1
    It converts char into int and compares. They’re both integers, there’s no problem in doing this. It’s called integral promotion. – Sami Kuhmonen Feb 13 '19 at 07:13
  • [Standard conersions](https://timsong-cpp.github.io/cppwp/n3337/conv). Specifically, [Integer Promotions](https://timsong-cpp.github.io/cppwp/n3337/conv#prom). – R Sahu Feb 13 '19 at 07:14
  • It's called "integer promotion". In your case `char` gets converted to `int` before performing comparison (ASCII code of `'C'` is 67). Same thing happens with other types shorter than `int`. – yeputons Feb 13 '19 at 07:14
  • 3
    Possible duplicate of [C comparison char and int](https://stackoverflow.com/questions/1010330/c-comparison-char-and-int) – gkamal Feb 13 '19 at 07:14
  • @SamiKuhmonen you mean to say, it is similar to `int` == `long int` comparison. – kvk30 Feb 13 '19 at 07:15
  • @gkamal, That one I saw but I added one more question please check it and answer it. – kvk30 Feb 13 '19 at 07:23
  • 1
    If you want to see what the CPU does, check out this for an x86 example: https://godbolt.org/z/2Zz3gS the `movsx` instruction means "move with sign extension", which is what is used to "upgrade" the `char` to be as big as an `int`, and then it is compared using the `cmp` instruction (which, below the hood, actually subtracts the values). – Blaze Feb 13 '19 at 07:24

1 Answers1

4

Their types are automatically (implicitly) converted and then are compared. https://www.learncpp.com/cpp-tutorial/44-implicit-type-conversion-coercion/

In short,

If an operand is an integer that is narrower than an int, it undergoes integral promotion (as described above) to int or unsigned int.

If the operands still do not match, then the compiler finds the highest priority operand and implicitly converts the other operand to match.

EDIT:

b == a, a == b do they come under same category of comparison? because in case of b == a(char comparing with int), in case of a == b(It is vice-versa)

Yes, they are the same. Regardless of their positions, char should be promoted to int type. If the bigger one converted into the smaller type, there is a chance to lose its value. So smaller one should be promoted to the bigger type.

Community
  • 1
  • 1
overfit
  • 349
  • 1
  • 12