Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How auto is deducing pointer type?

Tags:

c++

pointers

auto

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?

like image 603
PapaDiHatti Avatar asked Sep 11 '26 17:09

PapaDiHatti


2 Answers

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.

like image 50
David Haim Avatar answered Sep 13 '26 05:09

David Haim


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.

like image 33
skypjack Avatar answered Sep 13 '26 07:09

skypjack