strange unsigned char casting
What is the purpose / advantage / difference of using
/* C89 compliant way to cas开发者_开发技巧t 'char' to 'unsigned char'. */
static inline unsigned char
to_uchar (char ch)
{
return ch;
}
versus a standard cast ?
Edit : Found in a base64 code in gnulib
Maybe the programmer who wrote the function doesn't like the cast syntax ...
foo(to_uchar(ch)); /* function call */
foo((unsigned char)ch); /* cast */
But I'd let the compiler worry about it anyway :)
void foo(unsigned char);
char s[] = "bar";
foo(s[2]); /* compiler implicitly casts the `s[2]` char to unsigned char */
Purpose
To:
- Cast from
char
tounsigned char
- Do more with the cast than from a conventional cast
- Open your mind to the possibilities of customized casting between other types and select from the advantages below for those also
Advantage
One could:
- Break on these kinds of casts when debugging
- Track and quantify the use of casts through profiling tools
- Add limits checking code (pretty grim for
char
conversions but potentially very useful for larger/smaller type casts) - Have delusions of grandeur
- There is a single point of casting, allowing you to carefully analyze and modify what code is generated
- You could select from a range of casting techniques based on the environment (for example in C++ you could use
numeric_limits<>
) - The cast is explicit and will never generate warnings (or at least you can force choke them in one place)
Difference
- Slower with poor compilers or good compilers with the necessary optimization flags turned off
- The language doesn't force consistency, you might not notice you've forgotten to use the cast in places
- Kind of strange, and Java-esque, one should probably accept and study C's weak typing and deal with it case by case rather than trying to conjure special functions to cope
精彩评论