views:

254

answers:

4

In C++, I can change the operator on a specific class by doing something like this:

MyClass::operator==/*Or some other operator such as =, >, etc.*/(Const MyClass rhs) {
    /* Do Stuff*/;
}

But with there being no classes (built in by default) in C. So, how could I do operator overloading for just general functions?

For example, if I remember correctly, importing stdlib.h gives you the -> operator, which is just syntactic sugar for (*strcut_name).struct_element.

So how can I do this in C?

Thank you.

+15  A: 

Plain old C does not have operator overloading in any form. The -> "operator" to access a member of a pointer is standard C and is not introduced by any header file.

Mark Rushakoff
Indeed. `->` is just special syntax because pointers to structs are so common.
avpx
I see. So, basically, the only type of operator overloading would be some sort of preprocessor directive, say:#define plus(a,b) a+b. Although, that wouldn't allow for any form of parameters, unless you can somehow get it to change a and b to the actual parameter names...
Leif Andersen
@Leif: I don't think a macro is appropriate for what you're saying. If you want `struct foo` to have some notion of addition, then you would typically define a function `foo add_foos(foo lhs, foo rhs)` or something to that extent. There's no need to get the preprocessor involved in this. If you switch to C++ later, then you can overload `+` to call `add_foos`.
Mark Rushakoff
A: 

The -> structure pointer dereferencing operator is part of the C spec. stdlib.h does not affect this.

spoulson
Rats, okay, thank you. I remember a grad student at my university telling me that.
Leif Andersen
Don't trust a grad student to know anything about a language unless he's written an implementation of it himself. :)
greyfade
+2  A: 

Built-in operators in C language are overloaded. The fact that you can use binary + to sum integers, floating-point numbers and perform pointer arithmetic is a canonical example of operator overloading.

However, C offers no features for user-level operator overloading. You can't define your own operators in C.

AndreyT
A: 

Sure, you can't overload operators in C. The -> operator is part of the C language, no #include needed.