跳转至

分号

记住一句话:分号 ; 表示“一条语句或声明结束了”。
C++ 里大部分完整的“句子”末尾都要加分号,但后面直接跟大括号 {} 的代码块通常不加。

一、必须加分号的地方

场景 例子
变量、常量、对象定义 int a; string name; const double PI = 3.14;
赋值、运算、函数调用 a = 10; i++; cout << a;
函数声明(原型) int add(int a, int b);
类、结构体、枚举、联合体定义 class A { ... }; struct Point { int x; int y; };
using、typedef using namespace std; typedef int MyInt;
return、break、continue、goto return 0; break; continue;
do-while 的 while 后面 do { ... } while (x > 0);
空语句 ;

二、不要加分号的地方

场景 例子
预处理指令 #include <iostream> #define PI 3.14
函数定义结尾 int main() { ... } 后面不加
if / for / while / switch 的代码块后 if (x) { ... } for (...) { ... }
命名空间定义 namespace foo { ... }
标签 case 1: default:
访问修饰符 public: private: protected:
try / catch 代码块后 try { ... } catch (...) { ... }

三、容易搞混的特殊情况

  1. 函数声明 vs 函数定义
1
2
3
4
int add(int a, int b);   // 声明:加分号
int add(int a, int b) {  // 定义:后面的大括号后不加
    return a + b;
}
  1. 类定义 vs 函数定义
1
2
3
4
5
class A {
    void f() { }   // 成员函数定义,函数体后不加
};                 // 但类定义末尾必须加分号

void g() { }       // 普通函数定义,后面不加
  1. for 循环头里的分号
for (int i = 0; i < 10; i++) { ... }

这里的两个分号是语法分隔符,不是“语句结束”。

  1. 多写分号可能变成空语句
if (x > 0);        // 这个分号让 if 什么都没做
cout << "hello";   // 这行总会执行
  1. do-while 很特别
    1
    2
    3
    do {
        ...
    } while (x > 0);   // 这里必须加分号
    

四、一个小口诀

预处理、函数定义、控制块大括号后,不加;
变量、表达式、声明、类定义、do-while,加。

五、看一个完整例子

#include <iostream>      // 不加
using namespace std;     // 加

int add(int a, int b);   // 函数声明,加

int main() {             // 函数定义,不加
    int x = 1;           // 加

    if (x > 0) {         // 不加
        cout << x;       // 加
    }                    // 不加

    do {
        x--;
    } while (x > 0);     // 加

    return 0;            // 加
}                        // 不加

int add(int a, int b) {  // 函数定义,不加
    return a + b;        // 加
}                        // 不加

如果你写代码时编译器报 expected ';',通常就是某行该加分号却忘了。