my doubt is how is the operation done here, given that a character and an integers are two different data types?
I'm unsure how well this question will be received here, given it being about some fairly basic behavior of the language, but I commend you for thinking about type and type matching. Keep doing that!
The first thing to understand is that in C, char
and its signed and unsigned variants are among the integer data types, so there is no mismatch of type category, just a question of possibly-different range and signedness. Characters are represented by integer codes (as, indeed, is pretty much everything in the computer's memory).
The second thing to understand is that C supports all manner of arithmetic operations on operands of mixed types. It defines a set of "usual arithmetic conversions" that are used to choose a common type for the operands and the result of each arithmetic operation. The operands are automatically converted to that type. I won't cover all the details here, but basically, floating-point types win over integer types, and wider types win over narrower types.
The third thing to understand is that C does not in any case directly define arithmetic on integer types narrower than (technically, having integer conversion rank less than that of) int
. When a narrower value appears in an arithmetic expression, it is automatically converted to int
(if int
can represent all values of the original type) or to unsigned int
. These automatic conversions are called the "integer promotions", and they are a subset of the usual arithmetic conversions.
A fourth thing that is sometimes important to know is that in C "integer character constants" such as 'A'
have type int
, not type char
(C++ differs here).
So, to evaluate this ...
col = ch - 'A';
... the usual arithmetic conversions are first applied to ch
and 'A'
. This involves performing the integer promotions on the value of ch
, resulting in the same numeric value, but as an int
. The constant 'A'
already has type int
, so these now match, and their difference can be computed without any further conversions. The result is an int
, which is the same type as col
, so no conversion is required to assign the result, either.
How will the integer type hold the character value?
Character values are integer values. Type int
can accommodate all values that type char
can accommodate.* Nothing special is happening in that regard.
*Technically, int
can accommodate all values that can be represented by signed char
, unsigned int
can accommodate all values that can be represented by type unsigned char
, and at least one of the two can accommodate all values that can be represented by (default) char
. You are fairly unlikely to run across a C implementation where there are char
values that int
cannot accommodate, and the above assumes that you are not working with such an implementation, but these are allowed and some may exist.