c - 我如何找到在 C 中应该是常量的变量?

标签 c

所以,我得到了这段代码:

uint8_t* pbytes = pkt->iov[0].iov_base;

在结构中创建一个指向以太网数据包开头的指针。

然后我让我的 friend 查看代码,他说:“你没有修改它,如果你这样做会很困惑,所以把它设为 const”。

这似乎是个好主意,所以:

const uint8_t* pbytes = pkt->iov[0].iov_base;

甚至:

const uint8_t * const pbytes = pkt->iov[0].iov_base;

现在我在想,我敢打赌还有很多其他地方我可以做到这一点,而且我敢打赌编译器会比我更善于找到它们。

有什么办法可以问这个问题吗? (首选 gcc,但使用不同的编译器或 linting 工具没有问题,只要它们能在 unix 上运行)。

最佳答案

GCC 有一个标志来建议有用的属性,比如 const

-Wsuggest-attribute=[pure|const|noreturn|format] Warn for cases where adding an attribute may be beneficial. The attributes currently supported are listed below.

-Wsuggest-attribute=pure
-Wsuggest-attribute=const
-Wsuggest-attribute=noreturn
Warn about functions that might be candidates for attributes pure, const or noreturn. The compiler only warns for functions visible in other compilation units or (in the case of pure and const) if it cannot prove that the function returns normally. A function returns normally if it doesn’t contain an infinite loop or return abnormally by throwing, calling abort or trapping. This analysis requires option -fipa-pure-const, which is enabled by default at -O and higher. Higher optimization levels improve the accuracy of the analysis.

来源:http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

关于c - 我如何找到在 C 中应该是常量的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44119123/

相关文章:

将双指针转换为单指针,反之亦然

c -/usr/bin/env : ‘python’ : Permission denied---Problem while installing Ninja

c - 在c中动态增加数组(int *)的大小

c - 即使执行了 free 程序也会崩溃

python - 将 for 循环从 c 转换为 python

c - C 中的动态多维数组

c - C 中的链表访问冲突

无法理解为什么 c 中的 malloc 函数会如下所述执行操作?

c - C 中的 RLE 文本压缩

c - 为什么红黑树中的自引用哨兵比检查 NULL 更简单?