Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type cast a literal in C

I have a small sample function:

#define VALUE 0

int test(unsigned char x) {
  if (x>=VALUE)
    return 0;
  else
    return 1;
}

My compiler warns me that the comparison (x>=VALUE) is true in all cases, which is right, because x is an unsigned character and VALUE is defined with the value 0. So I changed my code to:

if ( ((signed int) x ) >= ((signed int) VALUE ))

But the warning comes again. I tested it with three GCC versions (all versions > 4.0, sometimes you have to enable -Wextra).

In the changed case, I have this explicit cast and it should be an signed int comparison. Why is it claiming, that the comparison is always true?

like image 582
Günther Jena Avatar asked Sep 01 '09 13:09

Günther Jena


3 Answers

Even with the cast, the comparison is still true in all cases of defined behavior. The compiler still determines that (signed int)0 has the value 0, and still determines that (signed int)x) is non-negative if your program has defined behavior (casting from unsigned to signed is undefined if the value is out of range for the signed type).

So the compiler continues warning because it continues to eliminate the else case altogether.

Edit: To silence the warning, write your code as

#define VALUE 0

int test(unsigned char x) {
#if VALUE==0
  return 1;
#else
  return x>=VALUE;
#endif
}
like image 171
Martin v. Löwis Avatar answered Oct 31 '22 18:10

Martin v. Löwis


x is an unsigned char, meaning it is between 0 and 256. Since an int is bigger than a char, casting unsigned char to signed int still retains the chars original value. Since this value is always >= 0, your if is always true.

like image 28
Corey D Avatar answered Oct 31 '22 19:10

Corey D


All the values of an unsigned char can fir perfectly in your int, so even with the cast you will never get a negative value. The cast you need is to signed char - however, in that case you should declare x as signed in the function signature. There is no point lying to the clients that you need an unsigned value while in fact you need a signed one.

like image 3
Bojan Resnik Avatar answered Oct 31 '22 20:10

Bojan Resnik