Search code examples
ctype-promotion

How come I can compare a char with an int?


I am not very familiar with C so I am a bit confused on the type safety of the language.

For example.

char* my_pointer;

my_pointer = malloc(sizeof(char));

if (*my_pointer == 0b0000)
{
    // this might be true or false, doesn't matter
}

How come the code runs? Why doesn't it just blow up at *my_pointer == 0b0000?

Shouldn't *my_pointer return a char?

So technically shouldn't only something like *my_pointer == 'a' be able to work?


Solution

  • C language does not have a dedicated "character" type with some isolated "character-only" semantics. char is just another integer type in C, just like, short or int. It just happens to be the smallest integer type. You can use char for integer arithmetic computations in the very same way you'd use any other integer type (albeit using char in that role is not a very good idea).

    When you are comparing char and int you are simply comparing two integer values. Nothing unusual about it.

    The rules of integer promotion say that char gets implicitly converted to int (provided the range fits) and then two int values are compared.

    Your *my_pointer == 'a' example is actually no different from your original one. In C 'a' is a character constant which represents an integer value of type int. I.e. there's no need to even promote 'a' to int since it is already an int.