Rohan
Rohan

Reputation: 31

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?

Upvotes: 1

Views: 175

Answers (3)

rekkalmd
rekkalmd

Reputation: 181

Mentioning the type indicates how your memory will store the data, in particular the number of memory cases, each type of data has its own size for example (see sizeof ()), working with low level languages sollicits attention on memory and hardware.

For example, the memory representation of a double is not the same as int, or any other type of data, even if they will print the same value as output (in case of implicite conversion), but in the stack, they are not completely the same "value". So the compiler will not allow this in case of pointers.

Using the keyword auto can manage what you are looking for.

Upvotes: 0

Lou Franco
Lou Franco

Reputation: 89152

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.

Upvotes: 8

imbr
imbr

Reputation: 7632

One possible reason is byte level manipulation of data.

For example, you can have a void* pointer (pointing tosome inner byte data) that can be acessed by *int or *char or whatever pointer you need depending on how you want to read or write data on it.

Upvotes: 0

Related Questions