Strange unsigned char casting

What is the purpose / advantage / difference of use

/* C89 compliant way to cast 'char' to 'unsigned char'. */ static inline unsigned char to_uchar (char ch) { return ch; } 

compared to standard litas?

Edit: Found in base64 code in gnulib

+6
c
source share
2 answers

Maybe the programmer who wrote this function doesn't like the translation syntax ...

 foo(to_uchar(ch)); /* function call */ foo((unsigned char)ch); /* cast */ 

But I would still think of a compiler :)

 void foo(unsigned char); char s[] = "bar"; foo(s[2]); /* compiler implicitly casts the `s[2]` char to unsigned char */ 
+1
source share

purpose

To:

  • Sent from char to unsigned char
  • Do more with cast than with conventional cast.
  • Open your mind to the possibilities of personalized casting between other types and choose from the advantages below for those who also

Advantage

It could be:

  • Break for these types of cast during debugging
  • Track and quantify throwing utilization using profiling tools
  • Add restriction checking code (rather gloomy for char conversions, but potentially very useful for larger / smaller types)
  • There are illusions of greatness
  • There is one casting point that allows you to carefully analyze and modify the code generated
  • You can choose from a range of casting methods based on the environment (for example, in C ++ you could use numeric_limits<> )
  • The cast is open and will never generate warnings (or at least you can force them to suppress in one place).

Difference

  • Slower with poor compilers or good compilers with optimization flags disabled.
  • The language does not force the sequence, you may not notice that you forgot to use the throw in places
  • Oddly enough, Java-esque should probably accept and learn C weak typing and process it in each case, and not try to call special functions to control
+1
source share

All Articles