Types, Operators and Expressions

从这一章节开始,将会采用常用的C标准


Variables and constants are the basic data objects manipulated in a program. Declarations list the variables to be used, and state what type they have and perhaps what their initial values are. Operators specify what is to be done to them. Expressions combine variables and constants to produce new values. The type of an object determines the set of values it can have and what operations can be performed on it. These building blocks are the topics of this chapter.

本章节将详细介绍各种变量类型,运算符以及表达式。

Variables Names

Names are made up of letters and digits; the first character must be a letter. The underscore ``_’’ counts as a letter; it is sometimes useful for improving the readability of long variable names.

变量名由字母和数字组成,第一个字符必须是字母。下划线_可以作为字母,在较长的变量名中可提高阅读性。变量不要以_开头,因为一些库的函数可能会以_开头,如_getchar()
注意,变量是区分大小写的,xX是完全不同的两个变量,在传统C开发中,一般变量用小写,常量用大写。

intcharfloatdouble等关键字不能作为变量名。

Data Types and Sizes

这有一些基本的数据类型:

  • int 表示整数,可以表示正负整数。
  • float表示浮点数,可以表示小数。
  • double表示双精度浮点数,可以表示小数。

另外,还有能表示更长或更短的数据形式比如shortlong,都是整型变量。一般int的长度会由编辑器决定,short一般是16bit,int 32bit或16bit都有可能,但是,shortint至少要高于16bit,long至少32bit,而且 short绝对比int短,且都必须比long短。

  • 关于singnedunsigned

  • signed表示有符号的,可以表示正负整数,unsigned表示无符号的,只能表示正整数。

  • 关于char, char表示字符,可以表示一个字符,如'a''b'

  • char的大小是8bit,但是char本质上是一个整数类型。这是因为 char 类型在内存中存储的是整数,这些整数对应于特定的字符编码(如 ASCII 编码)。这意味着 char 类型可以用来存储单个字符,同时也能够存储在该编码下的整数值。

  • 所以char也有符号之分,并且可以存储负数。

Constants

int 类型如1234long会加上L,如1234L。unsigned的类型会加上u或者U

int的进制可以为十进制,八进制和十六进制。

  1. 十进制:直接输入数字,如1234·
  2. 八进制:以0开头,如01234
  3. 十六进制:以0x0X开头,如0x1234
  4. 其他进制:如0b10100o1234

    为何没有二进制? 在 C 语言中,int 类型本身并不直接支持二进制字面量。直到 C99 标准之后,C 语言引入了 _Complex 和 _Imaginary 关键字,但这些与二进制字面量无关。直到 C11 标准,C 语言才正式支持了二进制字面量以及其他基数的字面量表示。

字符常量也是一种整型,在前文提到过,此处不再过多讲解。
关于转义字符,请看下表

转义字符 描述
\n 换行符
\t 制表符(水平制表)
\r 回车符
\b 退格符
\\ 反斜杠符
\' 单引号
\" 双引号
\0 空字符(NUL)
\v 垂直制表符
\f 换页符
\? 问号符(防止与三元运算符冲突)
\xhh 以十六进制表示的字符
\ooo 以八进制表示的字符

关于 \0有必要单独讲解

  • ‘\0’ 是一个特殊的字符,表示 空字符 或 null 字符。它的 ASCII 值为 0。
  • 在字符串中,’\0’ 通常用来标记字符串的结束。
  • 字符数组(即字符串)通常以 ‘\0’ 结束,以便字符串处理函数(如 strlen()、strcpy() 等)知道字符串的边界。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <string.h>

int main() {
char str[10] = "Hello"; // 字符串 "Hello"
str[5] = '\0'; // 手动添加 null 字符

printf("String: %s\n", str); // 输出 "Hello"

// 使用 strlen 计算字符串长度
int length = strlen(str);
printf("Length: %d\n", length); // 输出 5

return 0;
}

Declarations

All variables must be declared before use, although certain declarations can be made implicitly by content.

所有变量必须在使用前声明,尽管某些声明可以隐式地声明

  1. 显式声明:在变量名前加上类型,如int x;float y;char z;
  2. 隐式声明:在函数中,如果函数没有显式声明,那么函数中的变量会被隐式声明,如x = 1;y = 2.0;z = 'a';

限定字符const可以禁止变量被修改,如const int x = 1;const float y = 2.0;const char z = 'a';

建议在变量声明后赋初值,如int x = 1;float y = 2.0;如果不赋初值,会导致一些未知的问题和影响,甚至会使程序崩溃。

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

void example() {
int x; // 不赋初值的局部变量
printf("x = %d\n", x); // 输出未定义的值
}

int main() {
example();
return 0;
}