Thread: passing struct vs. reference

  1. #1
    Registered User
    Join Date
    Apr 2006

    passing struct vs. reference


    I don't know if I am getting the terminology quite correct, but hopefully people will understand what I mean and be able to give some advice.

    Is there any speed differences, or pros/cons, to passing a stucture in a function versus passing a reference to a structure? Here is what I mean, if I am using the wrong terms:

    passing a structure:
    void Init (MY_STRUCT struct);
    passing a reference:
    void Init (MY_STUCT *struct);
    I've never been able to find the differences explained in any textbooks. If someone knows where it is, I would like to know.


  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    In the first example (pass by value), the entire struct is copied onto the stack, in the second case, you pass the address to the struct (I will call this pass by pointer - the term reference is very similar, but not quite the same in syntax, and specific to C++). This has two consequences:
    1. Since you copy the struct, it's taking longer to perform the operation. This is usually a small factor, unless there is A LOT of calls to the function.
    2. You can modify the variable passed by value without modifying the original variable. This is sometimes exactly what you want, and sometimes exactly what you DON'T want. Choose wisely. If you want to pass by pointer, but not modify the contents, add "const" before the typename, e.g.
    void Init(const MY_STRUCT * ...)
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Apr 2006
    So if I understand you correctly, "passing by value" leaves the original MY_STRUCT untouched, even if I edit a member of MY_STRUCT in the function it is passed to?

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007

  5. #5
    Registered User
    Join Date
    Apr 2006
    Good to know, thanks..


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Assignment HELP!!
    By cprogrammer22 in forum C Programming
    Replies: 35
    Last Post: 01-24-2009, 02:24 PM
  2. Replies: 1
    Last Post: 12-03-2008, 03:10 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Passing by reference not always the best
    By franziss in forum C++ Programming
    Replies: 3
    Last Post: 10-26-2005, 07:08 PM
  5. Problem with OpenGL tutorial
    By 2Biaz in forum Windows Programming
    Replies: 18
    Last Post: 09-16-2004, 11:02 AM