C语言中的基本数据类型

从大一学习C语言起,至今10年有余,却对C语言中的基本数据类型始终是一知半解,人云亦云。今天看了C语言之父(Dennis Ritchie)写的程序设计语言的参考手册后,才终于有了一些自己的见解。

  简单点说,C语言的数据基本类型,分为两类:算数类型和void 空类型。(void类型常用来说明不返回任何值的函数类型和不传递任何形参的参数类型)

  下面主要讲讲算数类型。

  算数类型,也分为两类:浮点类型和整型类型。

  1.1 浮点类型

  三种: long double, double, float 

  注意:unsigned/signed 不能用于修饰浮点类型。浮点类型可以处理正数,也能处理负数,但是没有无符号浮点型。
  上述三者的大小关系:long double (12字节) > double (8字节)> float (4字节)

  1.2整数类型

   五种:char, short, int, long, 枚举类型(本质就是int型)

  unsigned/signed 可以用来修饰整数类型,即分为无符号整形数和有符号整形数。

  整数类型可以表示的最大数的大小关系(相同类型的无符号 > 有符号):

  unsigned long (4294967295) > long (2147483647) 
  unsigned long (4294967295) = unsigned int (4294967295) > int (2147483647) > unsigned short(65535 ) > short (32767)> unsigned char (255) > char (127)

  为了更好地理解,写了个小程序测试各数据类型的字节大小和则整形数能够表示的值范围。

程序源代码:
#include <stdio.h>
#include <limits.h>

int main()
{
	printf("The machine word len is %d\n",__WORDSIZE);
	printf("%-12s\t%2s\n","    Type","Size");
	printf("%-12s\t%2d\n","long double",sizeof(long double));
	printf("%-12s\t%2d\n","double",sizeof(double));
	printf("%-12s\t%2d\n","float",sizeof(float));
	printf("\n");
	printf("%-12s\t%2s\t%10s\t%10s\n","    Type","Size","Min","Max");
	printf("%-12s\t%2d\t%10d\t%10u\n","unsigned long",sizeof(unsigned long),0,ULONG_MAX);
	printf("%-12s\t%2d\t%10ld\t%10ld\n","long",sizeof(long int),LONG_MIN,LONG_MAX);
	printf("%-12s\t%2d\t%10d\t%10u\n","unsigned int",sizeof(unsigned int),0,UINT_MAX);
	printf("%-12s\t%2d\t%10d\t%10d\n","int",sizeof(int),INT_MIN,INT_MAX);
	printf("%-12s\t%2d\t%10d\t%10u\n","unsigned short",sizeof(unsigned short),0,USHRT_MAX);
	printf("%-12s\t%2d\t%10d\t%10d\n","short",sizeof(short),SHRT_MIN,SHRT_MAX);
	printf("%-12s\t%2d\t%10d\t%10u\n","unsigned char",sizeof(unsigned char),0,UCHAR_MAX);
	printf("%-12s\t%2d\t%10d\t%10d\n","char",sizeof(char),CHAR_MIN,CHAR_MAX);
	return 0;
}

运行结果:
rita@rita-desktop:~/work/c_program/exercise/ch2$ ./sizeof_type.exe 
The machine word len is 32
    Type     Size
long double  12
double       8
float        4


    Type        Size           Min             Max
unsigned long    4               0      4294967295
long             4      -2147483648     2147483647
unsigned int     4               0      4294967295
int              4      -2147483648     2147483647
unsigned short   2               0           65535
short            2          -32768           32767
unsigned char    1               0             255
char             1            -128             127
rita@rita-desktop:~/work/c_program/exercise/ch2$ 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值