当前位置:网站首页>C陷阱与缺陷 第2章 语法“陷阱” 2.6 “悬挂”else引发的问题
C陷阱与缺陷 第2章 语法“陷阱” 2.6 “悬挂”else引发的问题
2022-07-29 02:48:00 【weixin_客子光阴】
“悬挂”else引发的问题
if (x == 0)
if (y == 0) error();
else {
z = x + y;
f(&z);
}
编程人员的本意是应该有两种主要情况:x等于0以及x不等于0。对于x等于0,除非y也等于0(此时调用函数error),否则程序不作任何处理;对于x不等于0的情形,程序首先将x与y之和赋值给z,然后以z的地址为参数来调用函数f。
然而,这段代码实际上所做的却与编程者的意图相去甚远。原因在于C语言中有这样的规则,即else始终与同一对括号内最近的未匹配的if配合。
上面的程序实际上被执行的逻辑来调整代码缩进,大致如下:
if (x == 0) {
if (y == 0) error();
else {
z = x + y;
f(&z);
}
}
也就是说x不等于0,程序将不会做任何处理。如果要得到原来的例子中由代码缩进体现的编程者意图的结果,应该这样写:
if (x == 0) {
if (y == 0) {
error();
}
} else {
z = x + y;
f(&z);
}
原因在于第二个if已经被括号“封装”起来了。
有些C程序员通过使用宏定义也能达到类似的效果:
#define IF {if(
#define THEN ){
#define ELSE }else {
#define FI}}
这样,上例中的C程序就可以写成:
IF x == 0
THEN IF y == 0
THEN error();
FI
ELSE z = x + y;
f(&z);
FI
相当于
{
if(x == 0)
{
{
if(y == 0)
{
error();
}
}
}else
{
z = x + y;
f(&z);
}
}
还有一种方法就是为每个if语句配备一个else,这样就不会出现“悬挂”else的问题,不过会增加阅读的困难。
边栏推荐
- Notes on the sixth day
- Trample --- discretization + tree array + difference
- TP5.0 小程序用户无需登录,直接获取用户手机号。
- VASP calculation task error: M_ divide:can not subdivide 8 nodes by 6
- MySQL compound query (important)
- Thirty years of MPEG audio coding
- 【npm错误】- npm ERR code ERESOLVE 和 npm ERR ERESOLVE could not resolve 问题
- C language: Little Lele and hexadecimal conversion
- 明明开发薪资高,为什么我还是选了测试?
- Comic algorithm_ Xiaohuihui interview
猜你喜欢
随机推荐
13_ue4进阶_蒙太奇动画实现一边走一边攻击
多线程实现多用例文件并发读取执行+Selenium Grid4实现测试框架分布式部署
FTP protocol details
OWT server source code analysis (4) -- video module analysis of mixer out
Idea replaces the contents of all files
Why did I choose the test when the development salary was high?
金山云回港上市:中国TO B云厂商的港股奔袭
navicat新建数据库
Algorithm --- paint the house (kotlin)
Confusion matrix learning notes
FTP协议详解
vim常用命令
向DataFrame中的特定位置添加一行
SQL查询数据之多表(关联)查询
爆肝整理JVM十大模块知识点总结,不信你还不懂
常用hooks总结
.net serialize enumeration as string
Verilog's time system tasks - $time, $stime, $realtime
Plug in --- line segment sloth marking board + simple mathematical reasoning
Add a row to a specific location in the dataframe









