C中的每个变量都有一个关联的数据类型。每种数据类型需要不同数量的内存, 并具有一些可以在其上执行的特定操作。让我们一一简单地描述一下它们:
以下是C中使用的一些非常常见的数据类型的示例:
- char:C语言中最基本的数据类型。它存储一个字符, 几乎在所有编译器中都需要一个字节的内存。
- int:顾名思义, int变量用于存储整数。
- float:它用于以单精度存储十进制数字(带浮点值的数字)。
- double:它用于以双精度存储十进制数字(带浮点值的数字)。
不同的数据类型还可以存储数字的范围也不同。这些范围可能因编译器而异。以下是32位gcc编译器上的范围以及内存要求和格式说明符的列表。
数据类型 | 内存(字节) | 范围 | 格式说明符 |
---|---|---|---|
short int | 2 | -32, 768至32, 767 | %hd |
unsigned short int | 2 | 0至65, 535 | %hu |
unsigned int | 4 | 0至4, 294, 967, 295 | %u |
int | 4 | -2, 147, 483, 648至2, 147, 483, 647 | %d |
long int | 8 | -2, 147, 483, 648至2, 147, 483, 647 | %ld |
unsigned long int | 8 | 0至4, 294, 967, 295 | %鲁 |
long long int | 8 | -(2 ^ 63)至(2 ^ 63)-1 | %lld |
unsigned long long int | 8 | 0至18, 446, 744, 073, 709, 551, 615 | %llu |
signed char | 1 | -128至127 | %c |
unsigned char | 1 | 0至255 | %c |
float | 4 | %f | |
double | 8 | %lf | |
long double | 16 | %Lf |
我们可以使用sizeof()运算符检查变量的大小。有关各种数据类型的用法, 请参见以下C程序:
#include <stdio.h>
int main()
{
int a = 1;
char b = 'G' ;
double c = 3.14;
printf ( "Hello World!\n" );
//printing the variables defined above along with their sizes
printf ( "Hello! I am a character. My value is %c and "
"my size is %lu byte.\n" , b, sizeof ( char ));
//can use sizeof(b) above as well
printf ( "Hello! I am an integer. My value is %d and "
"my size is %lu bytes.\n" , a, sizeof ( int ));
//can use sizeof(a) above as well
printf ( "Hello! I am a double floating point variable."
" My value is %lf and my size is %lu bytes.\n" , c, sizeof ( double ));
//can use sizeof(c) above as well
printf ( "Bye! See you soon. :)\n" );
return 0;
}
输出如下:
Hello World!
Hello! I am a character. My value is G and my size is 1 byte.
Hello! I am an integer. My value is 1 and my size is 4 bytes.
Hello! I am a double floating point variable. My value is 3.140000 and my size i
s 8 bytes.
Bye! See you soon. :)