[C++]cpp小笔记3 --- C++基础类型的大小和转换

本文介绍了C++中不同整数类型(如short、int、long等)的大小,并通过示例展示了如何使用sizeof关键字来获取变量的大小。此外,还讲解了climits头文件中的常量值以及无符号类型和类型转换的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 类型的大小

  • A short integer is at least 16 bits wide.
  • An int integer is at least as big as short.
  • A long integer is at least 32 bits wide and at least as big as int.
  • A long long integer is at least 64 bits wide and at least as big as long.

2. sizeof and climits

int days = 0
cout << "size of days is " << sizeof(days) << endl;
cout << "size of int is " << sizeof(int) << endl;

Results:
size of days is 4
size of int is 4

climits中定义了c++中基础类型的最大值,最小值,大小的常量值。
CHAR_BIT          Number of bits in a char
CHAR_MAX       Maximum char value
CHAR_MIN        Minimum char value
SCHAR_MAX    Maximum signed char value
SCHAR_MIN     Minimum signed char value
UCHAR_MAX   Maximum unsigned char value
SHRT_MAX       Maximum short value
SHRT_MIN        Minimum short value
USHRT_MAX    Maximum unsigned short value

climits的使用
#include <climits>
// use limits.h for older systems


3.  无符号类型

unsigned short change;
unsigned int rovert;
unsigned quarterback;  //unsigned int type
unsigned long gone;
unsigned long long lang_lang;



从这张图上可以看出
If signed integer max value is 32767. 32767 + 1, result is -32768. 
If unsigned integer max value is 65535, if 65535 + 1, result is 0.

4. 类型转换。

自动类型转换:
  • C++会自动将converts bool, char, unsigned char, signed char, and short values to int.
  • The unsigned short type is converted to int if short is smaller than int. If the two types are the same size, unsigned short is con-
    verted to unsigned int. 
    This rule ensures that there’s no data loss in promoting unsigned short.
  • When an operation involves two types, the smaller is converted to the larger.
强制转换:

int a = 0;
double b = (double)a; 

OR 

double b = double(a);

double b = static_cast<double> (a);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值