6

Given:

void function(int*=0) {}
int main() {
}

clang (3.8.0):

test.cc:1:18: error: expected ')'
void function(int*=0) {
                 ^

g++ (5.4.0):

test.cc:1:18: error: expected ‘,’ or ‘...’ before ‘*=’ token
 void function(int*=0) {
                  ^    

If I change it to (note the spacing):

void function(int* = 0) {}
int main() {
}

Obviously it's getting confused whether I'm typing T* = 0 or T *= 0, is this a bug or expected?

gct
  • 14,100
  • 15
  • 68
  • 107

2 Answers2

18

*= is one operator, like += is. So x *= 2; is the same as x = x * 2;

You want * = to be lexed as two tokens (conceptually in C++, lexing happens before, and nearly independently, of parsing; read about C++ translation phases).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • but *= in this context makes completely no sense, why would compiler assume it is the multiply operator? – bartop May 31 '18 at 16:29
  • 11
    Because lexing & parsing are separate phases, conceptually – Basile Starynkevitch May 31 '18 at 16:30
  • @bartop see [my comment above](https://stackoverflow.com/questions/50628782/is-this-a-bug-in-clang-g#comment88267705_50628782) wrt to maximal munch. – Shafik Yaghmour May 31 '18 at 16:30
  • 5
    @bartop "_but *= in this context makes completely no sense_" True - it doesn't make sense, hence the reason why compiler complains about it. Tokenizer doesn't care about the context, it only cares about tokens, and `*=` is lexed as a single token. – Algirdas Preidžius May 31 '18 at 16:30
-2

There is a short way to multiply a value, like:

foo *= 2;

Which basically does the same as:

foo = foo * 2;

Maybe that's what it is confused about.

E. van Putten
  • 615
  • 7
  • 17