MoonOnAStick
MoonOnAStick

Reputation: 35

Printing type-cast types in C

#include <stdio.h>

int main(void) {
  int nr = 5;
  char castChar = (char)nr;
  char realChar = '5';
  printf("The value is: %d\n", castChar);
}

If the above code is compiled, the output will be:

The value is: 5

But if the code below is compiled, the console will output the value 53 instead. Why doesn't it print the same as the when the "castChar" is printed?

#include <stdio.h>

int main(void) {
  int nr = 5;
  char castChar = (char)nr;
  char realChar = '5';
  printf("The value is: %d\n", realChar);
}

Upvotes: 1

Views: 755

Answers (2)

jxh
jxh

Reputation: 70422

(char)5 and '5' are not the same thing.

The literal '5' is an integer value that represents the character 5. Its value depends on the platform. Assuming ASCII representation for characters, this would be 53.

The literal (char)5 is the integer value 5 that has been cast to type char. This means it retains the value of 5 after the cast.

Upvotes: 1

John Bode
John Bode

Reputation: 123468

Because the value of castChar is the integer value 5, while the value of realChar is the integer encoding of the character value '5' (ASCII 53). These are not the same values.

Casting has nothing to do with it. Or, more accurately, casting nr to char doesn't give you the character value '5', it just assigns the integer value 5 to a narrower type.

If you expect the output 5, then you need to print realChar with the %c specifier, not the %d specifier.

Upvotes: 3

Related Questions