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?
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.
The standard says:
The type of a variable declared using auto is deduced from its initializer.
Thus, the type of test is deduced from the one of ptr (that is its initializer) and it's int *.
Note that auto follows almost the same rules of template type deduction.
You can refer to them for further details about the differences between auto, auto&, const auto &, auto&& and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With