Wednesday, July 6, 2022

[FIXED] What are the considerations when returning by value vs by reference - Set ADT C

Issue

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!


Solution

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



Answered By - Antti Haapala -- Слава Україні
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.