4

The following code compiles in C but not in C++:

int *ptr = 25; //why not in C++?

Error

prog.cpp: In function ‘int main()’:
prog.cpp:6:11: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
  int *ptr = 25;

But this compiles in both C and C++:

int *ptr = 0;  //compiles in both

Why does assigning 0 work fine and other numbers does not work?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Chaitanya
  • 105
  • 9

1 Answers1

6

Because you can't implicitly convert from int to int* in C++, however 0 can, due to historical reasons, since it is often used as the value of NULL.

If you want to do it in C++, you need to explicitly cast the number to a pointer:

int *ptr = reinterpret_cast<int*>(25);
Tommy Andersen
  • 7,165
  • 1
  • 31
  • 50
  • 2
    It is not often used as value of `NULL`, 0 was official value in C++ before `nullptr` arrived. `NULL` is from C. – Slava Aug 03 '17 at 19:34
  • okay thanks! I'll check it out. @Tommy Andersen – Chaitanya Aug 03 '17 at 19:38
  • @Slava It is common for NULL to be #defined as 0 in C++ implementations - what other value (prior to nullptr) could it have? –  Aug 03 '17 at 19:41
  • @NeilButterworth I may not express myself clearly - statement that 0 is often used as the value of NULL and that the reason it works in C++ is incorrect. 0 is standard way to express `nullptr` in c++03 and that the reason. And because of that `NULL` is defined that way in C++ not vice versa. – Slava Aug 03 '17 at 19:53
  • @Slava in C++ `NULL` is implementation defined, `nullptr` was introduced in C++11, not C++03, in other words 0 is not the official definition of it. – Tommy Andersen Aug 03 '17 at 20:25
  • @TommyAndersen I just used it `nullptr` as a term, not keyword. 0 is valid and standard constant to represent null pointer in c++03. – Slava Aug 03 '17 at 20:28
  • @Slava yes 0 is a standard constant for null pointers, this was done to increase C compatibility. I you want to use `nullptr` as a term you might consider not marking it as a code, like: nullptr :) – Tommy Andersen Aug 03 '17 at 20:29