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:
example.c:5:8: warning: incompatible integer to pointer conversion initializing
'int *' with an expression of type 'int'
int *x = 17;
^ ~~
C99 says in Section 6.5.4 Cast operators, paragraph 4:
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 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:
Any type conversion not mentioned below and not explicitly defined by the user is ill-formed.
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.
Yes, the casting is implicit in C, although many (all?) compilers give a warning. In C++, no implicit conversion is performed from int
to int*
, so the explicit cast is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With