当前位置:嗨网首页>书籍在线阅读

18-类型大小

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

3.4.9 类型大小

如何知道当前系统的指定类型的大小是多少?运行程序清单3.8,会列出当前系统的各类型的大小。

程序清单3.8  typesize.c 程序

/* typesize.c -- 打印类型大小 */
#include <stdio.h>
int main(void)
{
     /* C99为类型大小提供%zd转换说明 */
     printf("Type int has a size of %zd bytes.\n", sizeof(int));
     printf("Type char has a size of %zd bytes.\n", sizeof(char));
     printf("Type long has a size of %zd bytes.\n", sizeof(long));
     printf("Type long long has a size of %zd bytes.\n",
               sizeof(long long));
     printf("Type double has a size of %zd bytes.\n",
              sizeof(double));
     printf("Type long double has a size of %zd bytes.\n",
              sizeof(long double));
     return 0;
}

sizeof 是C语言的内置运算符,以字节为单位给出指定类型的大小。 C99C11 提供 %zd 转换说明匹配 sizeof 的返回类型[2]。一些不支持 C99C11 的编译器可用 %u%lu 代替 %zd

该程序的输出如下:

Type int has a size of 4 bytes.
Type char has a size of 1 bytes.
Type long has a size of 8 bytes.
Type long long has a size of 8 bytes.
Type double has a size of 8 bytes.
Type long double has a size of 16 bytes.

该程序列出了 6 种类型的大小,你也可以把程序中的类型更换成感兴趣的其他类型。注意,因为C语言定义了 char 类型是 1 字节,所以 char 类型的大小一定是 1 字节。而在 char 类型为 16 位、 double 类型为 64 位的系统中, sizeof 给出的 double4 字节。在 limits.hfloat.h 头文件中有类型限制的相关信息(下一章将详细介绍这两个头文件)。

顺带一提,注意该程序最后几行 printf() 语句都被分为两行,只要不在引号内部或一个单词中间断行,就可以这样写。