Works in C, but not in C ++

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 fromint’ to ‘int*’ [-fpermissive]
  int *ptr = 25;

But this compiles in both C and C ++:

int *ptr = 0;  //compiles in both

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

+4
source share
1 answer

Because you cannot implicitly convert from intto int*to C ++, however 0 due to historical reasons can be caused by the fact that it is often used as a value NULL.

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

int *ptr = reinterpret_cast<int*>(25);
+6
source

Source: https://habr.com/ru/post/1682975/


All Articles