-4

in C++ when i run this code :

void main()
{
  2;
  +
  3;
}

there is no error but when i run this code :

void main()
{
  2;
  *
  3;
}

there is this error:

main.cpp:5:3: error: invalid type argument of unary ‘*’ (have ‘int’)
    5 |   3;
      |   ^

please someone explain it thanks

Blaze
  • 16,456
  • 1
  • 21
  • 43
Will
  • 37
  • 3
  • Excuse me, but why do you even need it? In which context expression-level operator is not enough? – Valeriy Savchenko Nov 15 '19 at 08:54
  • Note that [`void main()` is wrong](https://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c). `main` must have `int` return type. – walnut Nov 15 '19 at 09:28
  • I really dont get the downvotes. This question is clear and all understand what is asked. the why hinter the question should be blacked out. – skratchi.at Nov 15 '19 at 09:29

2 Answers2

10

Disregard the 2;, it's a statement on its own that doesn't do anything. Then, if we remove the whitespace, we get

+3;

Which is a valid expression. Like how -3; would also be valid. +3 is the same as 3. You can read about the unary plus here:

+ expression

unary plus (promotion).

For the built-in operator, expression must have arithmetic, unscoped enumeration, or pointer type. Integral promotion is performed on the operand if it has integral or unscoped enumeration type and determines the type of the result.

*3, on the other hand, is not meaningful. Unary * can't be applied to the literal 3.

Blaze
  • 16,456
  • 1
  • 21
  • 43
2

Since C++ is free style language. So space doesn't matter.

In first case it becomes +3 which is a valid statement. Read Here about +

But in second case it becomes *3 which is invalid as compiler thinks you are trying to dereference 3 which is invalid.

Problematic Dude
  • 1,025
  • 1
  • 3
  • 17