3

Why this code even compile? What is the meaning of "+ +" operator?

#include <string>
int main()
{
  std::string c = "abc";
  c = c + + "d";
  c = c + + + "d";
  c = c + + + + "d";
  c = c + + + + + "d";
  printf("%s\n", c.c_str());
}
Fan Yu
  • 83
  • 2
  • 1
    @LightnessRacesinOrbit It's the same thing; there is no operator `-->` in C just like there is no `+ +`. These are clumps of tokens mistaken as one operator. The fix is to fix one's understanding of C tokenization and syntax, parse the construct properly and then use a reference manual to understand the meaning of the actual operators. I picked that question because it was the first one on the list that came up for closing as duplicate which had anything to do with clumping of operators and thinking it's one. – Kaz Sep 29 '16 at 18:36

3 Answers3

10

There is no + + operator. There's a + operator (which occurs in both unary and binary forms), and a ++ operator, not used here.

Each of those is a binary + operator followed by one or more unary + operators.

This:

c = c + + "d";

is equivalent to

c = c + (+ "d");

This:

c = c + + + "d";

is equivalent to:

c = c + (+ + "d");

or:

c = c + (+ (+ "d"));

And so forth.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
2

That's just a lot of unary pluses.

Alexey Guseynov
  • 5,116
  • 1
  • 19
  • 29
2

The first + is a binary plus which calculates the sum of c and the second term.

The remaining + are unary plus operators. In + "d", "d" is of type const char[2], and decays to const char*. Then + is applied to the pointer which has no effect, and returns the same const char*.

c + + + "d" is equivalent to c + (+(+"d")).

tmlen
  • 8,533
  • 5
  • 31
  • 84
  • 1
    `"d"` has type `const char[2]`, not `char[1]`, and decays to `const char *`. –  Sep 29 '16 at 18:24
  • 1
    fixed. not sure if it is actually `const char* const` (const pointer) – tmlen Sep 29 '16 at 18:29
  • 1
    Prvalues of non-class types cannot be `const` or `volatile`-qualified, so it's just `const char *`. Simple testcase: `const char * &&str = "str";` –  Sep 29 '16 at 18:33