Home > database >  C operators overload, rules for spaces in expression
C operators overload, rules for spaces in expression

Time:04-02

I want to learn the rules (if any) about usage of spaces for writing correct operator overloads.

I've seen different forms:

T operator (T t1, T t2)   /* etc. */
T operator  (T t1, T t2)  /* etc. */
T operator  (T t1, T t2)  /* etc. */
T operator   (T t1, T t2) /* etc. */

I'm talking about the space(s) between the operator keyword, operator characters and first parenthesis.

Which one(s) is(are) correct? What is(are) the preferred one(s) over the others? Are some of them wrong, or, are some of them right in certain cases and wrong in others (and vice-versa)?

In short: do the spaces have any special meaning here (in this particular subject (I don't ask about use of spaces generally in code)?

If so, when and why? If not, what are considered as best practices?

CodePudding user response:

Other than in character and string literals, the only place in C code where whitespace is significant is to separate tokens that would be (or could be) otherwise merged.

In your case, there is a clear separation between the three tokens, operator, and (, so the added space characters make no difference whatsoever to how the compiler will interpret the declaration.

However, something like Toperator (T t1, T t2) is invalid, because the T and the operator will now be treated as a single (identifier) token.

As for which one is "best" – that's really a matter of taste and opinion, although cppreference generally uses the "no space" option for overload declarations.

  • Related