当前位置:网站首页>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的问题,不过会增加阅读的困难。
边栏推荐
- Verilog的时间系统任务----$time、$stime、$realtime
- Interpreting AI robots' pet raising and leading fashion trends
- 12. Writing rules - static mode
- 第09章_性能分析工具的使用
- Look at robot education and lead the mainstream of quality education
- MongoDB索引 (3)
- SQL查询数据之多表(关联)查询
- 算法---粉刷房子(Kotlin)
- R语言ERROR: compilation failed for package ‘****‘
- HTB-Blue
猜你喜欢

A good-looking IAPP donation list source code

New conch movie theme template m3.1 fully decrypted version multifunctional apple cmsv10 background adaptive theme open source fully decrypted version

K210 - sound source location and sound recognition

Small program source code for campus stray cat information recording and sharing / wechat cloud development medium big cat spectrum small program source code

HTB-Blocky

Etcd implementation of large-scale service governance application practice

PHP lucky draw system with background source code

MySQL - count(字段)、count(主键)、count(1)、count(*)的区别

DHCP协议详细解析

(job) C language: Simulation Implementation of ATOI and strncpy, strncat, strncmp
随机推荐
PHP process communication series (I) named pipes
centos安装mysql8
Verilog的时间系统任务----$time、$stime、$realtime
12. Writing rules - static mode
Self organization is the two-way rush of managers and members
Why did I choose the test when the development salary was high?
Mysql复合查询(重要)
MySQL 操作数据库数据报错:Fatal error encountered during command execution
idea配置web容器与war打包
K210 - sound source location and sound recognition
第2章 VRP命令行
JVM基础入门篇一(内存结构)
[QNX Hypervisor 2.2用户手册]9.11 ram(更新中)
Idea replaces the contents of all files
C语言:小乐乐与进制转换
VIM common commands
C language: judging letters
MySQL忘记密码怎么办
Add a row to a specific location in the dataframe
解析机器人与人类情感共鸣的主观意识