Why do C and C++ allow the expression (int) + 4*5?

C++CCastingLanguage Lawyer

C++ Problem Overview


(int) + 4*5;

Why is this (adding a type with a value) possible? (tried with g++ and gcc.)

I know that it doesn't make sense (and has no effect), but I want to know why this is possible.

C++ Solutions


Solution 1 - C++

The + here is unary + operator, not the binary addition operator. There's no addition happening here.

Also, the syntax (int) is used for typecasting.

You can re-read that statement as

(int) (+ 4) * 5;    

which is parsed as

((int) (+ 4)) * (5);    

which says,

  1. Apply the unary + operator on the integer constant value 4.
  2. typecast to an int
  3. multiply with operand 5

This is similar to (int) (- 4) * (5);, where the usage of the unary operator is more familiar.

In your case, the unary + and the cast to int - both are redundant.

Solution 2 - C++

This is interpreted as ((int)(+4)) * 5. That is, an expression +4 (a unary plus operator applied to a literal 4), cast to type int with a C-style cast, and the result multiplied by 5.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErnest BredarView Question on Stackoverflow
Solution 1 - C++Sourav GhoshView Answer on Stackoverflow
Solution 2 - C++Igor TandetnikView Answer on Stackoverflow