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 *
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;
These are the reasons I thought that in C, the casting was implicit.
Can someone please explain why, in C++, I have to cast it but in C, it works fine?
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:
C99 says in Section 6.5.4 Cast operators, paragraph 4:
6.5.16.1 is the exception for
void *converting to other pointers without needing a cast.The C++ spec says in Section 5.4 Explicit type conversion (cast notation), paragraph 3:
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.