Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell if a C integer variable is signed?

As an exercise, I'd like to write a macro which tells me if an integer variable is signed. This is what I have so far and I get the results I expect if I try this on a char variable with gcc -fsigned-char or -funsigned-char.

#define ISVARSIGNED(V) (V = -1, (V < 0) ? 1 : 0) 

Is this portable? Is there a way to do this without destroying the value of the variable?

like image 342
sigjuice Avatar asked Sep 11 '09 17:09

sigjuice


2 Answers

#define ISVARSIGNED(V)  ((V)<0 || (-V)<0 || (V-1)<0)

doesn't change the value of V. The third test handles the case where V == 0.

On my compiler (gcc/cygwin) this works for int and long but not for char or short.

#define ISVARSIGNED(V) ((V)-1<0 || -(V)-1<0)

also does the job in two tests.

like image 74
mob Avatar answered Sep 22 '22 15:09

mob


If you're using GCC you can use the typeof keyword to not overwrite the value:

#define ISVARSIGNED(V) ({ typeof (V) _V = -1; _V < 0 ? 1 : 0 })

This creates a temporary variable, _V, that has the same type as V.

As for portability, I don't know. It will work on a two's compliment machine (a.k.a. everything your code will ever run on in all probability), and I believe it will work on one's compliment and sign-and-magnitude machines as well. As a side note, if you use typeof, you may want to cast -1 to typeof (V) to make it safer (i.e. less likely to trigger warnings).

like image 25
Chris Lutz Avatar answered Sep 20 '22 15:09

Chris Lutz