Variables I and Arithmetic Types
TLDR 见 Summary / TLDR
Variable declaration
Type
- Type can not be changed
- Known even when the program is not run
- known at compile-time
- C is statically-typed <=> C has a static type system.
Arithmetic types
Integer
- signed or unsigned
intis optional (short int=short,unsigned int=unsigned)unsignedneeds to be written- Types without the keyword
unsignedare signed by default
- Types without the keyword
| type | width (at least) | width (usually) |
|---|---|---|
| short | 16 bits | 16 bits |
| int | 16 bits | 32 bits |
| long | 32 bits | 32 or 64 bits |
| long long | 64 bits | 64 bits |
-
Minimum Possible Width (最小可能宽度):这指的是该类型在任何平台上的最小位宽度,C标准规定数据类型的最小宽度。例如,
short类型被规定至少需要16位。这确保了程序在不同平台上的可移植性。 -
Typical Width (典型宽度):这指的是该类型在大多数常用平台上的典型位宽度。因为硬件和操作系统之间的差异,对于某些类型,尤其是
int和long类型,它们的宽度可能在不同系统上有所不同。例如,int类型在大多数现代系统上通常是32位,但也有一些旧系统使用16位。
- A
signedtype has the same width as itsunsignedcounterpart.
Implementation-defined behaviors 实现定义行为
The standard states that the exact width of the integer types is implementation-defined.
- Implementation: The compiler and the standard library.
- An implementation-defined behavior depends on the compiler and the standard library, and is often also related to the hosted environment (e.g. the operating system).
Real floating types
C has three types for representing real floating-point values:
- float : single precision. Matches IEEE754 binary32 format if supported.
- double : double precision. Matches IEEE754 binary64 format if supported.
- long double : extended precision. A floating-point type whose precision and range are at least as good as those of
double.
Do not use floating-point types for integer arithmetic!
Addition about limitations of floating types
1. 不能乱用
double midpoint(long long a, long long b) {
return (a + b) / 2.0;
}
// 9007199254740993 9007199254740993
2. 浮点误差
判断一个浮点数是否等于零, 必须使用 \(|x|<\epsilon\), 其中 \(\epsilon\) 可以是 \(10^{-8}\) 这样的一个小数。判断两个浮点数是否相等, 必须使用 \(|a-b|<\epsilon\) 。具体参考 IEEE 754
以下的例子输出:0.19999999999999998
scanf / printf
| type | format specifier |
|---|---|
| short | %hd |
| int | %d |
| long | %ld |
| long long | %lld |
| type | format specifier |
|---|---|
| unsigned short | %hu |
| unsigned | %u |
| unsigned long | %lu |
| unsigned long long | %llu |
| type | format specifier |
|---|---|
| %f | float |
| %lf | double |
| %Lf | long double |
Charater Type
- Size: 1 byte (any
chartype is smaller thanshort,int, ...)signed char: \([-128, 127]\)unsigned char: \([0, 255]\)
- Escape Charater
signed/unsigned: Implementation-defined%c- Questions on non-ASCII characters
Boolean Type
- Since C99:
1,0=>truefalse #include <stdbool.h>
Summary / TLDR
- 1 byte = 8 bit
- sizeof(T) 可以获得 T 所占的字节数量
- printf("%zu\n", sizeof(double));