Search code examples
c++pointersdereferencec++-concepts

In C++, why is mentioning the type of the pointer necessary?


In C++, mentioning the type of pointer is necessary. For example,

int a = 5;
int * p = &a;

Here, 'int' in the 'int *' was necessary. The reasons I found are that its needed for dereferencing.(Knowing no. of bytes to read, and their interpretation) and Pointer Arithmetic.

However, if I write:-

int a = 5;
char * p = &a;
float * p2 = &a;
//etc

Error is shown, saying that a char*,float* etc. pointer can't be assigned to an int variable. Ok.., so the compiler Knew the type of variable for whom I wanted a pointer for. This is unlike normal variables, where compiler doesn't know exactly which type I want. For example:-

int a = 5;
float b = 5;
double c = 5;
long d = 5;
char e = 5;

All these are perfectly fine. I need to write the type here as compiler won't know which type I want, as all of these would work.

However, in case of pointers, it knows the exact type of variable for which I want to declare a pointer to.

Even if I use explicit typecasting, still, I will be in a way telling the type of pointer I need, and still will have to specify the correct pointer type as well.

int a = 5;
char * b = (char*)&a;//This would work.
//However this,
int * b = (char*)&a;
//wouldn't, as even with typecasting, c++ knows exactly the type of pointer we need.

So, my question is, why doesn't C++ automatically set the type of pointer, when it knows the type of variable I am going to point to? When it can give error on not using the correct type of pointer, why not set it automatically?


Solution

  • If you declare b as auto, the compiler will use type inference and determine the type itself. But if you use a specific type, it has to be the correct one.