0

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?

SiggiSv
  • 1,219
  • 1
  • 10
  • 20
  • 1
    "the decimal value of the character result obtained by subtracting character 0 from character 5 will be equivalent to character 5" What? The value obtained by subtracting the character `'0'` from `'5'` is `5` but the value of the character `'5'` is `53`. How is that equivalent? – SiggiSv Jun 03 '17 at 10:28

2 Answers2

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.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

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.

Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36
  • 1
    Character constants are already type `int`, so `'0'` is not promoted to `int`. – ad absurdum Jun 03 '17 at 08:01
  • [character literals are `int` in C](https://stackoverflow.com/q/433895/995714), not `char` – phuclv Jun 03 '17 at 11:51
  • Nitpick: "a cast" (ie "an explicit conversion") can never be implicit. What can be implicit or explicit are "conversions". – pmg Jun 03 '17 at 12:04