Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange unsigned char casting

Tags:

c

What is the purpose / advantage / difference of using

/* C89 compliant way to cast '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

like image 914
shodanex Avatar asked Sep 08 '10 15:09

shodanex


2 Answers

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 */
like image 78
pmg Avatar answered Nov 06 '22 03:11

pmg


Purpose

To:

  • Cast from char to unsigned 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
like image 1
Matt Joiner Avatar answered Nov 06 '22 04:11

Matt Joiner