Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the C++ compiler really smart enough to distinguish between multiply and dereference?

I have the following line of code:

double *resultOfMultiplication = new double(*num1 * *num2);

How does the compiler know which * is used for derefencing and which * is used for multiplication?

Also, and probably a more important question is in this case is double a primitive (like in Java) or an object? If it's a primitive how can I create a new one?

like image 717
Nosrettap Avatar asked Oct 20 '25 14:10

Nosrettap


2 Answers

The compiler doesn't need to be "smart"; 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.

I shan't go into an in-depth proof that operator precedence exists in C++; for that, just take a basic course in syntax structure and you'll grok it soon enough.

like image 195
Lightness Races in Orbit Avatar answered Oct 22 '25 04:10

Lightness Races in Orbit


Maybe an analogy will help:

Q: How do humans tell the dot above the 'i' apart from the dot at the end of of a sentence? Are they really that smart that they don't interpret each and every 'i' as the end of the sentence?

A: Because they are in different locations!

Same is for the '*' for the compiler: they appear in different positions. The multiplication operator stands in the middle of two expressions; The dereferencing operator stands in front of an expression. It may not be obvious to you, but it is obvious to a compiler.

Any decent text on parsing will tell you how compilers are able to do this. The required technology was developed about 40 years ago, and is considered to be among the most basic things in a compiler. A C++ compiler has to have many smart parts, but this is not one of them.

Note to experts: I am aware of factors, lvalues, and so on. But they will only confuse in this case.

like image 22
Sjoerd Avatar answered Oct 22 '25 04:10

Sjoerd