Hi all,
Can someone explain this to me?
double number = 68.6;
printf("%c\n", number);
when i print the number as char, it displayed char 'f'. For ASCII code, lower case 'f' should be 102.
Hi all,
Can someone explain this to me?
double number = 68.6;
printf("%c\n", number);
when i print the number as char, it displayed char 'f'. For ASCII code, lower case 'f' should be 102.
Your code gives undefined behaviour (forcing printf() to treat number as if it was a char).
"Undefined", as that term is defined in the C standard, effectively means ANYTHING is allowed to happen. That can range from a program crash to printing output you do not expect.
thanks for reply:
It is actually a question like this:
int z=6;
int y=4;
double n=0.4;
char a = 'C';
printf("%c\n", z%y-n+a);
i can manage to debug it, but am just not sure why the answer could be 'f'.
z%y-n+a
The result of expression is double. variadic function like printf does not have type promotion.
So you are having undefined behavior.
so it will be no explanations for this undefined behavior? The answer could be any char depend on the result from z%y-n+a?
Nothing to do with ASCII?
A double is 8 bytes. The value 68.6 is encoded in some manner in those eight bytes - the "how" of that encoding depends on the floating point representation of your computer. printf() might be printing one of those bytes.
The problem is, because the behaviour is undefined, the code is allowed to do ANYTHING. There is a good chance, for example, that results will be different if you use another compiler. With yet another compiler, your code may simply reformat your hard drive (yes, unlikely, but not infeasible).
The bottom line is that you should not use "%c" format specifier for a value of type double.
Yes and no.
Going back to your original post, ASCII code for 'f' is 102 or binary (0110 0110). First byte of 68.6 in binary is also (0110 0110). You can see why your getting 'f' from printf(), then.
I wouldn't particularly count on this behavior, tho.
thanks! got it now!