当前位置:网站首页>C陷阱与缺陷 第7章 可移植性缺陷 7.9 大小写转换
C陷阱与缺陷 第7章 可移植性缺陷 7.9 大小写转换
2022-08-01 21:00:00 【weixin_客子光阴】
大小写转换
#define toupper(c) ((c) + 'A' - 'a')
#define tolower(c) ((c) + 'a' - 'A')
这两个宏都依赖于特定实现中字符集的性质,即需要所有大写的小写字母与相应的小写字母之间的差值是一个常量。因为这些宏不能移植,且这些宏被封装在一个文件中,所以这个假设也并不那么危险。
这些宏的不足之处:如果输入的字母大小写不对,那么它们返回的就都是无用的垃圾信息。
这段代码无法工作:
int c;
while ((c = getchar()) != EOF) {
putchar(tolower(c));
}
应该写成这样才对:
int c;
while ((c = getchar()) != EOF) {
putchar(isupper(c) ? tolower(c) : c);
}
#define toupper(c) ((c) >= 'a' && (c) <= 'z' ? (c) + 'A' - 'a' : (c));
#define tolower(c) ((c) >= 'A' && (c) <= 'Z' ? (c) + 'a' - 'A' : (c));
可能每次宏调用,致使c被求值1到3次。例如遇到toupper(*p++)这样的表达式。
int toupper(int c) {
if (c >= 'a' && c <= 'z') {
return c + 'A' - 'a';
}
return c;
}
健壮性得到增强,代价是引入了函数调用的开销。
因此引入了新的宏名:
#define _toupper(c) ((c) + 'A' - 'a');
#define _tolower(c) ((c) + 'a' - 'A');
边栏推荐
猜你喜欢

宝塔搭建PESCMS-Ticket开源客服工单系统源码实测

Questions I don't know in database kernel interview(1)

StringTable Detailed String Pool Performance Tuning String Concatenation

StringTable详解 串池 性能调优 字符串拼接

【Kaggle】Classify Leaves

WeChat applet cloud development | personal blog applet

Which websites are commonly used for patent searches?

案例:MySQL主从复制与读写分离

New graduate students, great experience in reading English literature, worthy of your collection

OSG笔记:设置DO_NOT_COMPUTE_NEAR_FAR,手动计算远近平面
随机推荐
案例:MySQL主从复制与读写分离
【Untitled】
有点奇怪!访问目的网址,主机能容器却不行
OSG Notes: Set DO_NOT_COMPUTE_NEAR_FAR to manually calculate far and near planes
STAHL触摸屏维修一体机显示屏ET-316-TX-TFT常见故障
乐观锁批量跟新 纯SQL
Hiking, cured my mental internal friction
wps excel 插入公式 整列
Internet使用的网络协议是什么
1374. 生成每种字符都是奇数个的字符串 : 简单构造模拟题
如何封装 cookie/localStorage/sessionStorage hook?
"No title"
Kubernetes 如何实现组件高可用
Convolutional Neural Network (CNN) mnist Digit Recognition - Tensorflow
Pytorch框架学习记录12——完整的模型训练套路
这些 hook 更优雅的管理你的状态
Go 语言中常见的坑
JS提升:如何中断Promise的链式调用
数据库单字段存储多个标签(位移操作)
响应式织梦模板清洁服务类网站