Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I implicitly convert an int literal to an int * in C but not in C++?

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?

like image 699
mmtauqir Avatar asked Sep 07 '25 16:09

mmtauqir


2 Answers

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.

like image 144
Carl Norum Avatar answered Sep 10 '25 06:09

Carl Norum


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.

like image 22
TonyK Avatar answered Sep 10 '25 05:09

TonyK