为什么我可以在 C 中将 int 文字隐式转换为 int * 而在 C++ 中不能?
我相信在下面的代码中,C自动将 17 转换为 int *
",正如最近有人指出的(但没有给出原因),这是错误的.
I believed that in the following code, C "automatically casts 17 to an int *
" which, as someone recently pointed out (but did not give the reasons as to why), is wrong.
int *ptoi = 17; // I assumed that 17 is being automatically casted to int *
我知道如果我在 C++ 中做与上面相同的事情,我会收到一个错误消息,说 invalid conversion from int to int *
.但是,如果我在 C++ 中执行以下操作,则效果很好:
I know that if I do the same thing as above in C++, I get an error saying invalid conversion from int to int *
. But if I do the following in C++, it works fine:
int *ptoi = (int *)17;
这些是我认为在 C 中强制转换是隐式的原因.
These are the reasons I thought that in C, the casting was implicit.
谁能解释一下为什么在 C++ 中,我必须强制转换它,而在 C 中,它可以正常工作?
Can someone please explain why, in C++, I have to cast it but in C, it works fine?
推荐答案
在 C 中,从整数到指针的转换在没有强制转换的情况下也是非法的.不过,大多数编译器会让你摆脱它.Clang 发出警告:
Conversions from integers to pointers without casts are also illegal in C. Most compilers will let you get away with it though. Clang gives a warning:
example.c:5:8: warning: incompatible integer to pointer conversion initializing
'int *' with an expression of type 'int'
int *x = 17;
^ ~~
C99 在第 6.5.4 节强制转换运算符,第 4 段中说:
C99 says in Section 6.5.4 Cast operators, paragraph 4:
涉及指针的转换,除非 6.5.16.1 的约束允许,应通过显式转换来指定.
Conversions that involve pointers, other than where permitted by the constraints of 6.5.16.1, shall be specified by means of an explicit cast.
6.5.16.1 是 void *
无需强制转换即可转换为其他指针的例外.
6.5.16.1 is the exception for void *
converting to other pointers without needing a cast.
C++ 规范在第 5.4 节显式类型转换(强制转换符号),第 3 段中说:
The C++ spec says in Section 5.4 Explicit type conversion (cast notation), paragraph 3:
以下未提及且未由用户明确定义的任何类型转换都是格式错误的.
Any type conversion not mentioned below and not explicitly defined by the user is ill-formed.
所以你去 - 在这两种语言中都是非法的,但是为了与许多旧软件的兼容性,很多 C 编译器会让你逃脱它.
So there you go - illegal in both languages, but for compatibility with lots of older software, a lot of C compilers will let you get away with it.
相关文章