当前位置:网站首页>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');
边栏推荐
- 数据库单字段存储多个标签(位移操作)
- Goroutine Leaks - The Forgotten Sender
- 15 分钟带你入门 Grafana
- 基于FPGA的任意字节数(单字节、多字节)的串口(UART)发送(含源码工程)
- 移植MQTT源码到STM32F407开发板上
- 【Kaggle】Classify Leaves
- Pytorch框架学习记录8——最大池化的使用
- Use WeChat official account to send information to designated WeChat users
- 徒步,治好了我的精神内耗
- LeetCode每日一题(1807. Evaluate the Bracket Pairs of a String)
猜你喜欢
Application of Acrel-5010 online monitoring system for key energy consumption unit energy consumption in Hunan Sanli Group
AQS原理和介绍
idea插件generateAllSetMethod一键生成set/get方法以及bean对象转换
网络安全与基础设施安全局(CISA):两国将在网络安全方面扩大合作
响应式织梦模板美容整形类网站
微信小程序云开发|个人博客小程序
SIPp installation and use
OSG笔记:设置DO_NOT_COMPUTE_NEAR_FAR,手动计算远近平面
微服务负载均衡器Ribbon
Little data on how to learn?Jida latest small learning data review, 26 PDF page covers the 269 - page document small data learning theory, method and application are expounded
随机推荐
PyTorch笔记 - Attention Is All You Need (2)
Common pits in the Go language
OSG笔记:设置DO_NOT_COMPUTE_NEAR_FAR,手动计算远近平面
自定义指令,获取焦点
外骨骼机器人(七):标准步态数据库
SkiaSharp 之 WPF 自绘 五环弹动球(案例版)
98.嵌入式控制器EC实战 EC开发板开发完成
tiup mirror init
使用百度EasyDL实现厂区工人抽烟行为识别
Nacos 配置中心
Zheng Xiangling, Chairman of Tide Pharmaceuticals, won the "2022 Outstanding Influential Entrepreneur Award" Tide Pharmaceuticals won the "Corporate Social Responsibility Model Award"
如何用Chrome编辑以及调试代码
"No title"
C专家编程 第1章 C:穿越时空的迷雾 1.1 C语言的史前阶段
任务调度线程池基本介绍
[Energy Conservation Institute] Application of Intelligent Control Device in High Voltage Switchgear
idea插件generateAllSetMethod一键生成set/get方法以及bean对象转换
【luogu P1912】诗人小G(二分栈)(决策单调性优化DP)
latex paper artifact -- server deployment overleaf
Little data on how to learn?Jida latest small learning data review, 26 PDF page covers the 269 - page document small data learning theory, method and application are expounded