PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

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

 July 06, 2022     adt, c, pass-by-reference, pass-by-value, set     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing