【C】数据类型
C语言允许使用的数据类型如下
graph LR
数据类型-->基本类型
基本类型-->a["整数类型( int )"]
基本类型-->b["浮点数类型(float、double)"]
基本类型-->c["字符类型( char )"]
基本类型-->d["布尔类型( _Bool )"]
基本类型-->枚举类型
数据类型-->指针类型
数据类型-->构造类型
构造类型-->数组类型
构造类型-->结构类型
构造类型-->联合类型
其中基本类型和枚举类型变量的值都是数值,统称算数类型。算数类型和指针类型统称为纯量类型。
graph TD
a["基本类型"]
a --> b["整数类型 <br><br> <ul> <li>short int</li>
<li>int</li>
<li>long int</li>
<li>long long int</li>
</ul>
short int≤ int ≤ long int ≤ long long int"]
a --> c["浮点数类型 <br><br> <ul> <li>float</li>
<li>double</li>
<li>long double</li>
</ul>"]
a --> d["字符类型 <br><br> <ul> <li>char</li> <br> <br> </ul>"]
a --> e["布尔类型 <br><br> <ul> <li>_Bool</li> <br> <br> </ul>"]
a --> f["枚举类型 <br><br> <ul> <li>enum</li> <br> <br> </ul>"]
sizeof运算符
-
sizeof运算符用于获得数据类型或表达式的长度。
- sizeof(object); // sizeof(对象,即变量名);
- sizeof(type_name); // sizeof(类型);
- sizeof object; // sizeof 对象;
#include <stdio.h> int main(){ int i; char j; float k; i = 123; j = 'C'; k = 3.14; printf("size of int is %d\n", sizeof(int)); printf("size of i is %d\n", sizeof(i)); printf("size of char is %d\n", sizeof(char)); printf("size of j is %d\n", sizeof j); printf("size of float is %d\n", sizeof(float)); printf("size of k is %d\n", sizeof k); return 0; }程序输出结构为
size of int is 4 size of i is 4 size of char is 1 size of j is 1 size of float is 4 size of k is 4我们可以利用sizeof来获取各个基本类型所占空间的大小
printf("int = %d\n",sizeof(int)); printf("short int = %d\n",sizeof(short)); printf("long int = %d\n",sizeof(long)); printf("long long int = %d\n",sizeof(long long)); printf("char = %d\n",sizeof(char)); printf("_Bool = %d\n",sizeof(_Bool)); printf("float = %d\n",sizeof(float)); printf("double = %d\n",sizeof(double)); printf("long double = %d\n",sizeof(long double));程序输出结果为:
int = 4 short int = 2 //short int ≤ int long int = 4 //int ≤ long int long long int = 8 //long int ≤ long long int char = 1 _Bool = 1 float = 4 double = 8 long double = 16注意:对于不同编译系统,它的值不一定相同。例如,在16位操作系统中,int所占空间大小为2
signed和unsigned
signed和unsigned是一对类型限定符,它们用于限定char类型或者任何整形变量的取值范围
- signed : 表示变量带符号位,说明该变量可以存放负数
- unsigned :表示该变量不带符号位,该变量只能存放正数和零,不能存放负数。相较signed,unsigned把存放负数的空间腾出来,存放更多的正数,所以unsigned可以存放更大的值。
因此四种整形在加上了signed和unsigned的限定符之后,就变成了八种。
- [signed] short [int] //中括号[]表示可选,即中括号内的内容可写可不写。
- unsigned short [int]
- [signed] int
- unsigned int
- [signed] long [int]
- unsigned long [int]
- [signed] long long [int]
- unsigned long long [int]
Tips:带unsiged表示强调它是一个不带符号的,就不能往里面存放负数,往里面存放一个负数就会出现问题。举个例子:
short i; //声明一个带符号变量i
unsigned short j; //声明一个无符号变量j
i = -1;
j = -1; //塞一个带符号的数进去
printf("%d\n",i); // 用带符号形式打印
printf("%u\n",j); // 用无符号形式打印
//%d打印带符号的,%u打印无符号的
程序输出结构:
-1 // i=-1成功打印出来
65535 //j打印出65535

浙公网安备 33010602011771号