Macro to test whether an integer type is signed or unsigned

If what you want is a simple macro, this should do the trick:

#define is_type_signed(my_type) (((my_type)-1) < 0)

Your requirement isn't exactly the best, but if you'd like to hack together a define, one option could be:

#define is_numeric_type_signed(typ) ( (((typ)0 - (typ)1)<(typ)0) && (((typ)0 - (typ)1) < (typ)1) )

However, this isn't considered nice or portable by any means.


In C++, use std::numeric_limits<type>::is_signed.

#include <limits>
std::numeric_limits<int>::is_signed  - returns true
std::numeric_limits<unsigned int>::is_signed  - returns false

See https://en.cppreference.com/w/cpp/types/numeric_limits/is_signed.


If you want a macro then this should do the trick:

#define IS_SIGNED( T ) (((T)-1)<0)

Basically, cast -1 to your type and see if it's still -1. In C++ you don't need a macro. Just #include <limits> and:

bool my_type_is_signed = std::numeric_limits<my_type>::is_signed;

Tags:

C++

C