How does the C/C++ compiler distinguish the uses of the * operator (pointer, dereference operator, multiplication operator)?
It depends from the context in which it is used, for a simple resolution it looks at the left and right word to understand what a symbol is.
The language's syntax is defined by a tree of grammatical productions that inherently imbue a priority or "precedence" to the application of certain operators over the application of other operators. This is particular handy when an expression might otherwise be ambiguous (because, say, two operators used are represented by the same lexical token).
But this is just lexing and parsing. Whether any particular operation is actually semantically valid is not decided until later in compilation; in particular, given two pointers x
and y
, the expression *x *y
will fail to compile because you cannot multiply *x
by y
, not because there was a missing operator in what might otherwise have been a dereference followed by another dereference.
Further read at wikipedia page: Lexer_hack.
Other interesting read at this Lexer-Hack Enacademic link.
- deferencing
*
operator is an unary operator so in trivial cases compiler will apply an implicit rule. eg
int a;
int *ptr = &a;
*ptr = 5;
- multiplication operator
*
is a binary operator so in trivial cases compiler will apply multiplication provided the operands support it eg:
int a;
int b;
int c = a*b;
- For more complex operations you might need to help the compiler understand what you mean by using parenthesis if the operators precedence is not enough eg:
int a = 1;
int b[2] = {2,3};
int *aPtr = &a;
int *bPtr = b;
int c = *aPtr * *(bPtr+1);