下面是我关于 C 语言中各种数据类型长度的总结: ( 参考 The C Programming Language)
1. c 语言中的整数类型有 char, short, int, long 等几种 , 下面是 C 语言对每种数据类型长度的规定 :
(a). short 和 long 类型的长度不相同
(b). int 类型通常同具体机器的物理字长相同
(c). short 通常是 16bits, int 通常是 16bits or 32bits 每种编译器可以根据硬件的不同自由确定 , 但是 short 和 int 必须最少是 16bits, 而 long 类型必须最少是 32bits, 并且 short 必须比 int 和 long 类型要短。
2. sizeof() 运算符返回的是一种数据类型中所包含的字节数 (bytes), AnsiC 规定 sizeof(char) 必须返回 1 ,当 sizeof 作用于数组时 , 返回的是数组中所有成员所占的字节数 ( 注意并不是数组中成员的个数 ), 当 sizeof() 作用于结构体和公用体时 , 返回的不仅仅是数据成员总的字节数 , 还包括编译器为了实现字节对其而填充的那些字节。
以前写程序也隐隐约约的懂得这些规则,但是一直以为 char 类型必须是 8bits 的,但是最近做了一个嵌入式 DSP 项目,编译器手册上明明写着 char 类型就是 16bits 的,无奈翻出 "The C Programming Language" 一查才发现 ANSI C 对于 char 类型的长度并没有作硬性规定。以前写程序不太注意数据类型的可移植性 , 这次项目中用到的以前的代码都要重新检查数据类型长度的问题。
C Data types.
Variable definition
C has a concept of 'data types ' which are used to define a variable before its use.
The definition of a variable will assign storage for the variable and define the type of data that will be held in the location.
So what data types are available?
Please note that there is not a boolean data type. C does not have the traditional view about logical comparison, but thats another story.
Recent C++ compilers do have a boolean datatype.
int - data type
int is used to define integer numbers.
|
float - data type
float is used to define floating point numbers.
|
double - data type
double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes.
|
char - data type
char defines characters.
|
Modifiers
The three data types above have the following modifiers.
- short
- long
- signed
- unsigned
The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules:
|
What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is:
Type Bytes Bits Range |
|
These figures only apply to todays generation of PCs. Mainframes and midrange machines could use different figures, but would still comply with the rule above.
You can find out how much storage is allocated to a data type by using the sizeof operator.