How, in C and C++ languages, can the compiler distinguish *
when used as a pointer (MyClass* class
) and when used as a multiply operator (a * b
) or when is a dereferencing operator (*my_var
)?
Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.
We can use the addressoperator to obtain its address, whatever it may be. This address can be assigned to a pointervariable of appropriate type so that the pointer points to that variable. The dereference operator (*) is a unary prefix operator that can be used with any pointer variable, as in *ptr_var.
The unary operator * is used to declare a pointer and the unary operator & is used to dereference the pointer.. In both cases, the operator is “unary” because it acts upon a single operand to produce a new value.
1.4 Indirection or Dereferencing Operator ( * ) As illustrated, a variable (such as number ) directly references a value, whereas a pointer indirectly references a value through the memory address it stores. Referencing a value indirectly via a pointer is called indirection or dereferencing.
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.
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