为什么我能隐式转换为int的文字为int *在C,但不是在C ++? [英] Why can I implicitly convert an int literal to an int * in C but not in C++?
问题描述
我认为在以下code,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 ++同样的事情,我从int到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.非法大多数编译器将让您摆脱它虽然。铛发出警告:
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段:
这涉及到指针,不包括依据的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是例外无效*
转换为其它指针而不需要转换。
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.
这篇关于为什么我能隐式转换为int的文字为int *在C,但不是在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!