Which of the following is a more suitable way to "auto" display the type of pointer?

(Very basic question :) I found that both methods generate a type below int *. Can I find out which one is more correct?

int i = 42;
auto a = &i;
auto *b = &i;

(I tried to associate an example pointer with an example link: auto c = i;and auto &d = i;. But the analogy doesn't seem to work here.)

Edit: I also found another (closely related) example:

auto i = 42, p = &i; // fails at compilation
auto i = 42, *p = &i; // passes at compilation

Why? In both cases, initializers have the same base int type (which both cases should do), right?

+4
source share
2 answers

IMO "", /, i. int *c = &i;. , typedef , int.

auto , , - for().

: auto - ( ), auto a = ..., auto *a = .... -, , . - / .

2: :

auto i = 42, p = &i; // fails at compilation

? . , . auto , auto . " ", ( ), .

, , , :

auto i = (int)42, p = (auto*)&i;

auto int:

int i = (int)42, p = (int*)&i;

, :

int i = (int)42;
int p = (int*)&i; // Whoopsie!
+1

:

auto a = &i;

, "a" . .

:

auto *b = &i;

, b int, b int * ( )

int i = 42; 
auto a = &i; // auto resolves to an int*
auto *b = &i; // auto resolves to an int (contents of b is int), b is an auto* aka int*

auto i = 42, p = &i; // auto resolves to an int, then p must also be an int (whoops mixing types).
auto i = 42, *p = &i; // auto resolves to an int, p is an auto* aka an int*
0

Source: https://habr.com/ru/post/1547273/


All Articles