Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the C/C++ compiler distinguish the uses of the * operator (pointer, dereference operator, multiplication operator)?

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)?

like image 632
Pinnaker Avatar asked Oct 08 '20 07:10

Pinnaker


People also ask

How is * used to dereference pointers?

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.

What is the use of (&) address operator and dereferencing (*) operator?

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.

Which C operator is used to dereference a pointer?

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.

What is the difference between dereference operator and pointer?

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.


1 Answers

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.

like image 114
Zig Razor Avatar answered Oct 22 '22 23:10

Zig Razor