4 ms·
> Notice that printf("%c", c) has pretty damned clear behavior, and it requires someone to say the equally-clear printf("%d", (int)c) to get a number when they
by nuxi 16y ago
> Notice that printf("%c", c) has pretty damned clear behavior, and it requires someone to say the equally-clear printf("%d", (int)c) to get a number when they want a number;
It does have a clear behaviour, but it's possibly different from what you think. From your examples I'm assuming "c" is a char variable - since you're casting it to int in the second example - which is then (incorrectly) passed to printf with "%c". Both %c and %d require an integer parameter, so "c" should be an integer to begin with (thus no need for a cast).
Nitpicking, I know, but such code can lead to many subtle bugs.
- makecheck 16y agoThe C library should cast the parameter down to a char when "%c" is used; the only reason it allows an int is for the "%lc" case.
- nuxi 16y agoIt does cast it down (to unsigned char). The requirement for int however was is not for "%lc", it was already in C89. I suspect it has to do with default integral promotions for (variadic) function parameters - which I incorrectly disregarded when replying. So the original code is correct, my reply wasn't.