【发布时间】:2017-08-03 19:28:53
【问题描述】:
以下代码在 C 中编译,但在 C++ 中不编译:
int *ptr = 25; //why not in C++?
错误
prog.cpp: In function ‘int main()’:
prog.cpp:6:11: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
int *ptr = 25;
但这在 C 和 C++ 中都可以编译:
int *ptr = 0; //compiles in both
为什么分配 0 可以正常工作,而其他数字则不行?
【问题讨论】:
-
究竟是什么错误?
-
因为
0在指针上下文中具有特殊含义。 -
0是一个空指针常量;25不是有效的指针常量。第一个不应该在没有警告的情况下在 C 中编译。