判断有符号和无符号数和符号

面试也会常考这种题,当然平常谁会在意呢?

有符号自然有正负,无符号就只有正了。

先上代码:

#define IsSignedNum(x) (x>=0 && -x>=0)
#define IsSignedType(type) ((type)-1<0)

分析上面的代码:

若x为int的+1和-1,+1>=0 && -1>=0为false。-1>=0 && 1>=0为false;

若x为unsigned int的1,1>=0 && 255>=0为true。因为无符号转为有符号的就用其补码了。

若type为int,(int)-1=-1<0为true;

若type为unsigned int,(unsigned int)-1=255<0为false。

原文地址:https://www.cnblogs.com/wyc199288/p/5206292.html