0

When looking at the header file of Set ADT in C, I'm trying to understand why was the function setUnion or setIntersection declared that way:

Set setUnion(Set set1, Set set2); 
Set setIntersection(Set set1, Set set2);

I couldn't find the implementation but I'm assuming that inside those functions, we allocate more space and create new set, and then add all the necessary elements. I thought that set1 and set2 are passed by reference, so why not update one of them and save mem allocations and just return some enum that notifies whether the update succeeded or not? (for example we can update the left parameter).

If they're not passed by reference, how can I change the signature in order to do so?

Thank you!

E. Ginzburg
  • 253
  • 2
  • 9
  • 2
    Please show the definition of `Set`. – Weather Vane Sep 16 '19 at 07:12
  • This isn't a sensible API so you are right in questioning it. In proper C programs we don't pass structs/ADTs by value, and we don't hide pointers behind typedefs. This API is violating one of those two rules. In addition, there's no const correctness. Quite some code smell. – Lundin Sep 16 '19 at 09:26

1 Answers1

1

The Set almost certainly is a pointer hidden behind a typedef, so there is an actual pass by reference of the internal struct which is all that counts.


More often than not one needs to calculate a union or an intersection of two sets without mutating either of them. In fact it is quite probable that

Set result = setIntersection(set1, set2);
freeSet(set1);
set1 = result;

Would not be any less performant than your proposed alternative

setIntersectionInPlace(set1, set2);

Whereas the more common case of calculating an intersection of immutable sets using setIntersectionInplace would need to be written

Set result = setCopy(set1);
setIntersectionInplace(result, set2);

Which would make a needless copy of a set1, which is larger, or equal in size to size of result

  • The proper way of using immutable parameters would have been to use `const`-qualified pointers though. If `Set` is a pointer hidden behind a typedef, then it can't be const qualified or the returned `Set` would be, too. The most likely explanation is simply that whoever wrote the API didn't know what they were doing. – Lundin Sep 16 '19 at 09:29
  • 2
    @Lundin that is very likely! And in general the pointer typedefs are frowned upon, unless one subcribes to the Microsoft Systems Hungarian notation and types like `LPCSETFARPTRCSTDIOAFXSTFU`... – Antti Haapala -- Слава Україні Sep 16 '19 at 09:30