快速读懂 C++ 中的 signed、unsigned、long 和 short 修饰符(C++复习向p7)

时间:2025-02-23 10:42:08

几种类型支持的修饰符

  • 整型:signed、unsigned、long、short
  • 字符型:signed、unsigned
  • 双精度型:long

修饰符的含义

  • signed:标识变量可以存负数,整型默认就是这样

  • unsigned:相反的,不能存负数,但会让变量范围扩大一倍

  • short:变量范围比 int 更小

  • long:变量范围比 int 更大

代码举例

unsigned 范围更大,但存不了负数的案例:

short int i = 50000;
short unsigned int j = 50000;
cout << i << endl << j; // 最终的输出是 -15536 和 50000

short、long 和 long long (C++11的新规范) 的几种用法:

short int num1;

long int num2;
long long int num3;
long long num4; // long 后的 int 可以省略

long double num5; // 双精度可以用 long 修饰 ~