I am trying to overload some operators:
/* Typedef is required for operators */
typedef int Colour;
/* Operators */
Colour operator+(Colour colour1, Colour colour2);
Colour operator-(Colour colour1, Colour colour2);
Colour operator*(Colour colour1, Colour colour2);
Colour operator/(Colour colour1, Colour colour2);I get this error for each tried overloading:
expected '=', ',', ';', 'asm' or '__attribute__' before '+' tokenI can't find any good documentation on operator overloading. Googling results in C++ tutorials which use classes. In C there are no classes. Can anyone help me? Thanks.
57 Answers
C does not support operator overloading (beyond what it built into the language).
7There is no operator overloading in C.
1You need a time machine to take you back to 1985, so that you may use the program CFront. It appears that 'C' use to support operator overloading; to the sophisticated enough it still can. See Inside the C++ Object Model by Stanley B. Lippman. OMG, C++ was C! Such a thing still exists.
This answer confirms the others. 'C' by itself does not directly support overloading. However, the important point is a programmer can write code that understands code. You need a tool that transforms source to implement this. In this case, such tools already exist.
A paper, Meta-Compilation for C++, 2001 by Edward D. Willink has interesting examples of design functionality, where extending a language is useful. The combination of *nix shell script and make rules often allow such transformation. Other examples are Qt MOC, the tools Lex and Yacc, halide etc. So while 'C' itself doesn't accommodate this directly, it does if you build host tools.
In this particular example the overloading may not make sense. However, it could make a lot of sense for a program needing arbitrary precision math.
3You cannot overload these operators in C.
C does not support operator overloading at all.
You can only implement operations as functions:
Colour colour_add(Colour c1, Colour c2);
Colour colour_substract(Colour c1, Colour c2);
...You could also switch to C++, but it may be overkill to do it just for the overloading.
2Operator overloading is not available in C. Instead, you will have to use a function to "pseudo-overload" the operators:
Colour add_colours(Colour c1, Colour c2) { return c1 + c2; // or whatever you need to do
} If you want comparable concision, the use of macros is the best available alternative:
void Type_getSomething(int id); //or some other complex series of instructions
#define g(id) Type_getSomething(id)...it's such a pity that the use of square brackets isn't possible for macros!