Kapil Kapil - 2 months ago 5
C++ Question

How auto is deducing pointer type?

In below code I could not understand how

auto
comes to know that thing on right hand side is pointer :

int x = 100;
int *ptr = & x;
auto test = ptr;
std::cout<<*test<<std::endl;


Because as per my understanding pointer contains address which is nothing but
unsigned int
so how
auto
deduces it to be pointer but not
unsigned int
?

Answer

you can also ask the question "eventually, everything in my program is bytes, so why does auto doesn't deduce everything to be uint8_t[]?"

Well, it's simple. the type of ptr is int* so the type of test is also int*. it doesn't matter how the generated assembly looks like. it may be that the cpu treats int* and unsigned int the same way, but that's irrelevant for C++, as C++ is a high level language.

besides that. the underlying statement that "a pointer is an unsigned int" is not true. pointer is a type that allows reading and writing to the memory address contained in that variable. an unsigned int is ... an unsigned int. nothing more, nothing less.

Comments