C++ 常量 : how come the compiler doesn't give a warning/error

标签 c++ constants

关于 C++ 常量性的非常简单的问题。

所以我正在读这个post ,然后我尝试了这段代码:

int some_num = 5;
const int* some_num_ptr = &some_num;

为什么编译器不给出错误或至少不给出警告?

我阅读上面声明的方式是这样说的:

Create a pointer that points to a constant integer

但是 some_num 不是常量整数——它只是一个整数。

最佳答案

问题在于您阅读代码的方式。它实际上应该读作

Create a pointer to an integer where the value cannot be modified via the pointer

C++ 中的 const int* 不保证 int 是常量。它只是一个工具,使通过指针修改原始值变得更加困难

关于C++ 常量 : how come the compiler doesn't give a warning/error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2246996/

相关文章:

C++ 字符串追加问题

constants - BCPL 八进制数值常数

c++ - 在预处理指令后避免对(生成的) token 发出 gcc 警告?

c++ - 文件存在时出现 Visual Studio 外部符号错误

c++ - 如何在内联 ASM 中调用此函数? (MSVC++)

c++ - 如何将私有(private)指针作为 const 返回到指针列表?

c++ - MSVS 2012 "ambiguous call to overloaded function"中的编译器错误

c++ - 如何避免实现 const 和非 const 迭代器的代码重复?

c++ - const * const 的预处理器简写

c++ - 多集 STL 中的下界