Search code examples
ccasting

Typecasting a float to char


I'm self-learning C and was experimenting with typecasting. I tried to typecast a float to a char and this was my code:

# include <stdio.h>
int main() {
  float a = 3.14;
  int c = 3;
  int d;
  d = (int)a*c;
  printf("I am printing a typecasted character %c", (char)d);
  return 0;
}

The output I got was this:

$ clang-7 -pthread -lm -o main main.c
$ ./main
I am printing a typecasted character $

The character never got printed and I don't know what went wrong. Please help.


Solution

  • It all looks fine to me!

    To better see what happened, print it as a %i in addition to %c so you can see what the decimal number value is.

    (run me)

    #include <stdio.h>
    
    int main(){
        float a = 3.14;
        int c = 3;
        int d;
        d = (int)a*c;
        printf("I am printing a typecasted character, \"%c\", or signed decimal "
               "number \"%i\".\n", (char)d, (char)d);
        return 0;
    }
    

    Output:

    I am printing a typecasted character, "   ", or signed decimal number "9".
    

    Looking up decimal number 9 in an ASCII table, I see it is "HT", \t, or "Horizontal Tab". So, that's what you printed. It worked perfectly.

    @Some programmer dude has a great comment that is worth pointing out too:

    To nitpick a little: You don't cast a floating point value to char anywhere. In (int)a*c you cast the float variable a to an int. The multiplication is an integer multiplication. The integer result is stored in the integer variable d. And you cast this integer variable to a char, but that will then be promoted to an int anyway.