Reputation: 528
Is there a way to overload the comparators in C so that we can compare structs using >
, =
, and <
For example:
struct point {
int x, y;
}
struct point pt1 = make_point(2, 4);
struct point pt2 = make_point(2, 3);
we could have it compare on the y
value (or some arbitrary member of the struct).
if (pt1 > pt2)
{
printf("Point 1 is greater than Point 2\n");
}
and it would print out, Point 1 is greater than Point 2
since 4 > 3.
Upvotes: 1
Views: 602
Reputation: 18203
As others have said C does not support operator overloading. This kind of programming paradigm is usually accomplished in C by passing a comparator operation using a function pointer. For example see qsort in the standard library.
Upvotes: 1
Reputation:
No, C does not support operator overloading. The best you can have is writing a comparator function.
Upvotes: 1
Reputation: 38163
No, this is not possible. This is a C++ feature.
You should write some function, that does this and use it like: if( is_greater( pt1, ptr2 ) )
something like this.
Upvotes: 2
Reputation: 477000
No, you cannot overload operators in C. You cannot even overload ordinary functions in C.
Upvotes: 3