C 基本类型
预计时间: 4分钟
基本类型
关键字 | 描述 |
---|---|
char | 字符 |
int | 整数 |
float | 浮点数 |
double | 双精度浮点数 |
void | 无值 |
void 类型
类型说明符 void 表示没有可用的值。它用于三种情况
- 函数返回值类型 例如
void exit(int status);
- 函数参数类型 例如
int rand(void);
- 指针指向的类型 例如
void *malloc(size_t size);
C类型修饰符
关键字 | 描述 |
---|---|
signed | 有符号 |
unsigned | 无符号 |
long | 长型 |
short | 短型 |
修改符影响最小取值范围
C类型空间占用和取值范围
C语言标准只规定了每种数据类型都要覆盖一个确定的最小取值范围,没有定义它们各占多少字节。
要在特定平台上获取类型或变量的确切大小,可以使用 sizeof 运算符。表达式 sizeof(type) 产生对象或类型的存储大小(以字节为单位)。
在头文件中预定义了与具体实现相关的最小取值范围
<limits.h>
定义了一些表示整型大小的常量。<float.h>
定义了与浮点算术运算相关的常量。
常用类型存储大小
类型 | 大小(字节) | 格式说明符 |
---|---|---|
int | 至少 2 个,通常是 4 个 | %d ,%i |
char | 1 | %c |
float | 4 | %f |
double | 8 | %lf |
short int | 2 通常 | %hd |
long int | 至少 4 个,通常是 8 个 | %ld ,%li |
long long int | 至少 8 个 | %lld ,%lli |
unsigned int | 至少 2 个,通常是 4 个 | %u |
unsigned long int | 至少 4 | %lu |
unsigned long long int | 至少 8 个 | %llu |
signed char | 1 | %c |
unsigned char | 1 | %c |
long double | 至少 10 个,通常是 12 或 16 个 | %Lf |
/* data_types.c */
#include <stdio.h>
int main() {
int a;
char b;
float c;
double d;
short int e;
long int f;
long long int g;
unsigned int h;
unsigned long int i;
unsigned long long int j;
signed char k;
unsigned char l;
long double m;
short x_short;
long x_long;
long long x_long_long;
printf("size of int = %lu bytes\n", sizeof(a));
printf("size of char = %lu bytes\n", sizeof(b));
printf("size of float = %lu bytes\n", sizeof(c));
printf("size of double = %lu bytes\n", sizeof(d));
printf("size of short int = %lu bytes\n", sizeof(e));
printf("size of long int = %lu bytes\n", sizeof(f));
printf("size of long long int = %lu bytes\n", sizeof(g));
printf("size of unsigned int = %lu bytes\n", sizeof(h));
printf("size of unsigned long int = %lu bytes\n", sizeof(i));
printf("size of unsigned long long int = %lu bytes\n", sizeof(j));
printf("size of signed char = %lu bytes\n", sizeof(k));
printf("size of unsigned char = %lu bytes\n", sizeof(l));
printf("size of long double = %lu bytes\n\n", sizeof(m));
printf("size of short = %lu bytes\n", sizeof(x_short));
printf("size of long = %lu bytes\n", sizeof(x_long));
printf("size of long long = %lu bytes\n", sizeof(x_long_long));
return 0;
}
编译:
cc var.c -o var
输出:
size of int = 4 bytes
size of char = 1 bytes
size of float = 4 bytes
size of double = 8 bytes
size of short int = 2 bytes
size of long int = 8 bytes
size of long long int = 8 bytes
size of unsigned int = 4 bytes
size of unsigned long int = 8 bytes
size of unsigned long long int = 8 bytes
size of signed char = 1 bytes
size of unsigned char = 1 bytes
size of long double = 16 bytes
size of short = 2 bytes
size of long = 8 bytes
size of long long = 8 bytes
更新于2022年04月06日