Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Dereference operator used to declare pointers?

Why is the * used to declare pointers?

It remove indirection, but doesn't remove any when you declare a pointer like int *a = &b, shouldn't it remove the indirection of &b?

like image 695
Paralax01 Avatar asked Dec 30 '22 12:12

Paralax01


2 Answers

Many symbols in C and C++ are overloaded. That is, their meanings depend on the context where they are used. For example, the symbol & can denote the address-of operator and the binary bitwise AND operator.

The symbol * used in a declaration denotes a pointer:

int b = 10;
int *a = &b,

but used in expressions, when applied to a variable of a pointer type, denotes the dereference operator, for example:

printf( "%d\n", *a );

It also can denote the multiplication operator, for example you can write:

printf( "%d\n", b ** a );

that is the same as

printf( "%d\n", b * *a );

Similarly, the pair of square braces can be used in a declaration of an array, like:

int a[10];

and as the subscript operator:

a[5] = 5;
like image 66
Vlad from Moscow Avatar answered Jan 07 '23 10:01

Vlad from Moscow


Any time you have a pointer declaration with initialization like this:

type *x = expr;

it is equivalent to the separate initialization followed by assignment:

type *x;
x = expr;

It is not equivalent to

type *x;
*x = expr;      /* WRONG */
like image 35
Steve Summit Avatar answered Jan 07 '23 09:01

Steve Summit