Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro to test whether an integer type is signed or unsigned

Tags:

c++

c

How would you write (in C/C++) a macro which tests if an integer type (given as a parameter) is signed or unsigned?


      #define is_this_type_signed (my_type) ...

like image 835
botismarius Avatar asked Sep 15 '08 17:09

botismarius


People also ask

How do you know if a variable is signed or unsigned?

A numeric variable is signed if it can represent both positive and negative numbers, and unsigned if it can only represent non-negative numbers (zero or positive numbers).

Is integer signed or unsigned?

The XDR standard defines signed integers as integer. A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295].

Can we compare signed int with unsigned int?

while comparing a>b where a is unsigned int type and b is int type, b is type casted to unsigned int so, signed int value -1 is converted into MAX value of unsigned**(range: 0 to (2^32)-1 )** Thus, a>b i.e., (1000>4294967296) becomes false. Hence else loop printf("a is SMALL!

Is int automatically signed?

An int type in C, C++, and C# is signed by default. If negative numbers are involved, the int must be signed; an unsigned int cannot represent a negative number.


2 Answers

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.

like image 87
ChrisN Avatar answered Sep 30 '22 18:09

ChrisN


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

#define is_type_signed(my_type) (((my_type)-1) < 0)
like image 28
Fabio Ceconello Avatar answered Sep 30 '22 18:09

Fabio Ceconello