views:

161

answers:

5

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 '+' token

I 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.

+9  A: 

You cannot overload these operators in C.

Pierre-Antoine LaFayette
+12  A: 

There is no operator overloading in C.

Justin Ardini
Of course there is -- just for example, `-`, `+`, `/`, `*`, all apply equally well to `int` or `double`. What it doesn't support is adding any overloads beyond what's built in.
Jerry Coffin
Yes, of course. Your answer is indeed more clearly worded.
Justin Ardini
+7  A: 

C does not support operator overloading (beyond what it built into the language).

Jerry Coffin
+4  A: 

C does not support operator overloading at all.

You can implement operators only 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 just to do it just for the overloading.

Roberto Bonvallet
Writing a C library in C++ would be quite funny. Including the header file gives instant errors :)
Time Machine
+3  A: 

Operator 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
}
bta