6.1 简单语句
6.2 声明语句
6.3 复合语句(块)
6.4 语句作用域
6.5 if语句
- 悬垂else (dangling-else) 问题:当一个if子句多于else子句时,对于每一个else,究竟属于哪个if。
C++中会将else匹配给最后出现的尚未匹配的if子句。
6.6 switch语句
- 对于switch结构,只能在它最后一个case标号或default标号后面定义变量:
case true:
//error: declaration precedes a case label
string feil_name = get_file_name();
break;
case false;
// ...
- 制定这个规则是为了避免出现代码跳过变量的定义和初始化的情况。如果要定义变量,使用块语句{...}。
6.7 while语句
// arr1 is an array of ints
int *source = arr1;
size_t sz = sizeof(arr1)/sizeof(*arr1); // number of elements
int *dest = new int[sz]; // uninitialized elements
while(source != arr1 + sz)
*dest++ = *source++; //copy element and increment pointers
*dest++ = *source++;:优先级++ > *(代表结合先后,不是执行先后,见5.5)
完全等价于:
int temp = *source;
source = source + 1;
*dest = source;
dest = dest + 1;
6.8 for循环语句
- 可以在for语句的 init-statement 中定义多个对象,但是只能出现一个语句,因此所有的对象必须具有相同的一般类型:
const int size = 42;
int val = 0,ia[size];
//ival is an int,pi a pointer to int,and ri a reference to int
for(int ival = 0,*pi = ia,&ri = val; ival != size;++ival,++pi,++ri)
// ...
6.9 while语句
- 与while语句不同,do while语句总是以分号结束
- 如果在循环条件中定义变量,则对变量的任何使用都将发生在变量定义之前
6.10 break语句
6.11 continue语句
6.12 goto语句
6.13 try块和异常处理
6.13.1 throw表达式
6.13.2 try块
6.14 使用预处理器进行调试
- NDEBUG 预处理变量
大多数编译器都提供定义 NDEBUG 的命令行选项:
$ CC -NDEBUG main.c
这样的命令行等效于在 main.c 的开头提供 #define NDEBUG 预处理命令
- assert(断言)预处理宏(preprocessor macro)
- 异常用于处理程序执行时预期要发生的错误;
断言来测试“不可能发生”的条件