Search code examples
ctypecast-operator

In C, to convert character to an integer is it necessary to do typecast


In C, is it necessary to typecast character to an integer when we are eventually going to subtract character 0 from a number character to get its equivalent figure in an integer?

The aim of the following examples is to convert character 5 to its equivalent figure in an integer.

char a = '5';

int x = a - '0'; Here the decimal value of the character result obtained by subtracting character 0 from character 5 will be equivalent to character 5.

int i = (int)a; Here the decimal value of the character 5 will be assigned as it is even after doing typecast.

So what's the point of doing typecast when it shows no effect on its operand?


Solution

  • The conversion can be implicit (precision is not lost)

    int x = a;
    

    or explicit

    int x = (int)a;
    

    more exactly it is integer promotion and it is done before operation

    int x = ((int)a) - '0';
    

    in C '0' character literal is already int, whereas in C++ it is a char.