user5155804
user5155804

Reputation:

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?

Upvotes: 0

Views: 63

Answers (2)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

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.

Upvotes: 1

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

Readability of code (or conformance to the C programming language specified in n1570).

BTW, most typecasts are not translated to any machine code by an optimizing compiler.

Upvotes: 1

Related Questions