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.
CodePudding user response:
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
charanywhere. In(int)a*cyou cast thefloatvariableato anint. The multiplication is an integer multiplication. The integer result is stored in the integer variabled. And you cast this integer variable to achar, but that will then be promoted to anintanyway.
CodePudding user response:
Adding in some extra debug for the other variables shows why this is the case:
#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, %f, %d, %d", (char)a, a, c, d);
return 0;
}
Output: I am printing a typecasted character , 3.140000, 3, 9
Character 9 is not in the printable ASCII range, hence nothing useful prints.
It's not clear from your question what you're expecting, but perhaps you meant %d in the format string? Or maybe you wanted to start from the printable range (char)a 32 or (char)a '0' or something else.
Note also: many of those casts are to smaller types, so there's good chances for issues there.
