c - 我可以让 C 函数使用外部变量,而不让它修改它们吗?
问题描述
如果我有一个 C 函数使用的全局变量“x”
int foo() {
extern int x;
return x;
}
我可以禁止 foo 修改 x 吗?即以与下面的替代方法相同的方式对待 x?
int foo(const int x) {
return x;
}
解决方案
方法一:常量拷贝
#define HorribleHackStart(Type, Name) \
Type HorribleHackTemp = Name; { const Type Name = HorribleHackTemp;
#define HorribleHackEnd \
}
int foo(void)
{
HorribleHackStart(int, x)
... Here x is an unchanging const copy of extern x.
... Changes made to x (by other code) will not ge visible.
HorribleHackEnd
}
方法二:指针
int foo(void)
{
#define x (* (const int *) &x)
... Here x is effectively a const reference to extern x.
... Changes made to x (by other code) will be visible.
#undef x
}
注释
我不会在生产代码中使用其中任何一个,但如果您想编译代码以测试函数内部是否违反了 x 的 const 要求,它们可能会很有用。
推荐阅读
- cryptography - WalletConnect、MetaMask 和非托管钱包
- php - 使用 Tiny Editor 插入时出现一些随机字符
- nuget - 将 nuget 包的内容文件复制到输出目录
- javascript - 从对象数组中获取值
- node.js - 使用 Node.js 从文本文件中解析街道地址
- slurm - 在 SLRUM 集群的一个节点上运行多个 mpiexec
- jq - 按路由过滤 openapi 规范
- excel - Openpyxl:按值查找单元格地址的函数
- python-3.x - skimage 霍夫圆检测——检测到粒子边缘但未绘制圆
- php - 从 AWS Glacier 下载文件时如何找到文件的扩展名?