默认情况下,C中的所有整数类型都是有符号的。有符号数据类型可以包含正值和负值。
可以使用signed关键字显式声明有符号数据类型。
#include <stdio.h>
int main() {
signed char myChar; /* -128 to +127 */
signed short myShort; /* -32768 to +32767 */
signed int myInt; /* -2^31 to +2^31-1 */
signed long myLong; /* -2^31 to +2^31-1 */
signed long long myLL; /* -2^63 to +2^63-1 */
}
可以将整数类型声明为unsigned以使其上限为double类型。
#include <stdio.h>
int main() {
unsigned char uChar; /* 0 to 255 */
unsigned short uShort; /* 0 to 65535 */
unsigned int uInt; /* 0 to 2^32-1 */
unsigned long uLong; /* 0 to 2^32-1 */
unsigned long long uLL; /* 0 to 2^64-1 */
}
在printf中,说明符%u用于unsigned char,short和int类型。unsigned long类型用%lu指定,unsigned long long用%llu指定。
#include <stdio.h>
int main() {
unsigned int uInt = 0;
printf("%u", uInt); /* "0" */
}
执行上面示例代码,得到以下结果:
0
signed和unsigned关键字可以单独用作类型,在这种情况下,编译器假定int类型。
#include <stdio.h>
int main() {
unsigned uInt; /* unsigned int */
signed sInt; /* signed int */
}
同样,short类型和long类型是short int和long int的缩写。
#include <stdio.h>
int main() {
short myShort; /* short int */
long myLong; /* long int */
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/266427.html