Skip to content

C 基本语法

了解了 C 语言的基本程序结构后,接下来让我们深入探讨 C 语言的基本组成要素和语法规则。

一个 C 程序由称为 标记 (tokens) 的基本元素组成。编译器将源代码解析成这些标记。标记的主要类别包括:

  • 关键字 (Keywords): 具有特殊含义的保留字(例如,int, if, else, while, return)。
  • 标识符 (Identifiers): 用于命名变量、函数、类型等的名称(例如,main, age, calculateSum)。
  • 常量 (Constants): 固定值(例如,10, 3.14, 'A', "Hello")。
  • 字符串字面量 (String Literals): 用双引号括起来的字符序列(例如,"Hello, World!\n")。
  • 运算符 (Operators): 用于执行操作的符号(例如,+, -, *, /, =, ==, &, *)。
  • 标点符号 (Punctuators/Separators): 逗号、分号、括号、花括号等符号(例如,,, ;, (, ), {, })。

考虑以下语句:

printf("Value = %d\n", count);

这里的标记是:

`printf` (Identifier)
`(` (Punctuator)
`"Value = %d\n"` (String Literal)
`,` (Punctuator)
`count` (Identifier)
`)` (Punctuator)
`;` (Punctuator)

在 C 语言中,分号充当语句终止符 (statement terminator)。每个独立的语句(一个完整的指令)必须以分号结尾。它向编译器表明一个逻辑命令的结束。

两个独立语句的示例:

int age = 25;
printf("Age is %d\n", age);

注释是代码中用于解释的文本,会被编译器忽略。它们对于使代码易于人类理解至关重要。

C 语言支持两种注释风格:

  1. 多行注释 (Multi-line comments): 以 /* 开始,以 */ 结束。可以跨越多行。
  2. 单行注释 (Single-line comments) (C99+): 以 // 开始,并持续到当前行的末尾。
/* This is a multi-line comment.
It can span several lines.
Useful for longer explanations. */
int temperature = 20; // This is a single-line comment.
// Another single-line comment explaining the next line.
float price = 99.95; /* You can even put multi-line comments here */

注意:多行注释不能嵌套(/* ... /* ... */ ... */ 是无效的)。注释也不会出现在字符串字面量或字符字面量内部(例如,"Hello /* not a comment */ world")。

标识符是您给变量、函数、结构体、枚举、typedef 等实体起的名字。标识符的规则如下:

  • 必须以字母 (A-Z, a-z) 或下划线 (_) 开头。
  • 后续字符可以是字母、数字 (0-9) 或下划线。
  • 不能是 C 语言的关键字。
  • 区分大小写 (case-sensitive)(myVar 和 myvar 是不同的标识符)。
  • 有一个标准定义的最小有效长度,但现代编译器通常支持很长的名称。

避免以 _ 开头命名标识符,因为这类名称通常保留用于实现或标准库 (standard library)。

有效标识符:

count
user_name
_temporary
processData
item1
MAX_VALUE

无效标识符:

1stPlace (starts with a digit)
user name (contains a space)
my-value (contains a hyphen)
int (is a keyword)
rate$ (contains invalid character '$')

关键字是 C 语言保留的、具有预定义含义的词。您不能将它们用作标识符。

标准 C 关键字(包括 C99 和 C11):

| auto | break | case | char | const | continue | | default | do | double | else | enum | extern | | float | for | goto | if | inline (C99) | int | | long | register | restrict (C99) | return | short | signed | | sizeof | static | struct | switch | typedef | union | | unsigned | void | volatile | while | _Alignas (C11) | _Alignof (C11) | | _Atomic (C11) | _Bool (C99) | _Complex (C99) | _Generic (C11) | _Imaginary (C99) | _Noreturn (C11) | | _Static_assert (C11) | _Thread_local (C11) | | | | |

空白符是指空格、制表符、换行符等字符。C 编译器通常使用空白符来分隔标记,但会忽略多余的空白符。

例如,int 和 age 之间需要空白符来分隔:

int age; // 正确:空白符分隔了关键字和标识符
// intage; // 错误:编译器将 'intage' 视为一个未知标记

然而,多余的空白符通常会被忽略:

int count = 0 ; // Valid, though poorly formatted
x=a+b; // Valid, but less readable
x = a + b; // Valid and more readable

请一致地使用空白符(空格、制表符、空行)来格式化您的代码,以提高可读性。大多数项目都遵循特定的编码风格指南。