Thread: C/C++ - passing by reference - * or &

  1. #1
    Registered User
    Join Date
    May 2015
    Posts
    56

    C/C++ - passing by reference - * or &

    Hello,

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void inc(float*);
    void inc2(float*);
    void doub(float&);
    
    void inc(float* j)
    {
        (*j)++;
    }
    
    void inc2(float* k)
    {
        (*k) += 1.5768;
        printf("%2.4f\n", *k);
    }
    
    void doub(float& z)
    {
        z = z + z;
        printf("%2.3f\n", z);
    }
    
    int main()
    {
        float i = 20;
        float *p = &i;
        float x = 20;
    
        inc(p); //C & C++
        printf("%2.3f\n", i);
        inc2(p); //C & C++
        printf("\n");
    
        doub(x); //C++ not C
        printf("%2.3f\n", x);
        return 0;    
    }
    Code:
    Output :-
    21.000
    22.5768
    
    40.000
    40.000
    Both methods work, but generally which is better to use, passing by *(pointer) or &(address)?

    Regards

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,728
    In the case of C, your only option is a pointer.

    For C++ however, it depends on what you want to do. Generally I use pointers for arrays and references for single objects. That said, I can avoid the use of arrays entirely by means of an encapsulating object such as a vector, a string, a set etc. Yeah, I tend not to use pointers as arguments to functions anymore.
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    May 2015
    Posts
    56
    Hello,

    Thanks for your reply.
    In the case of C, your only option is a pointer.
    I'd realised that.

    It seems it's a matter of preference. If one is doing heavy work, is one method faster than the other?
    I guess I could time some loops and see what happens.

    Regards

  4. #4
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Quote Originally Posted by mad-hatter View Post
    If one is doing heavy work, is one method faster than the other?
    References will never be slower than pointers, and may be faster.

    Quote Originally Posted by mad-hatter View Post
    I guess I could time some loops and see what happens.
    Not a bad idea. There are profiler tools out there, that will give you detailed info on where your program is taking the most time. You don't have to do manual timing.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  5. #5
    Registered User
    Join Date
    May 2010
    Posts
    4,437
    It seems it's a matter of preference. If one is doing heavy work, is one method faster than the other?
    You really shouldn't be too worried about which is faster, you should be worried about which is less error prone and easier to read and understand.

    IMO in C++ you should prefer using references where ever possible and only use pointers when absolutely necessary.

    Jim

  6. #6
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    I actually like Google's C++ style guide in this one respect. Arguments that are meant to be read from are references and arguments that are meant to be written to are pointers. I kind of like that for some reason.

    But in general, in C++ you should avoid pointers unless it doesn't make sense to use one of the other language constructs like std::vector or std::array.

  7. #7
    Registered User
    Join Date
    May 2015
    Posts
    56
    Hello,

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    void inc(float*);
    void inc2(float&);
    
    void inc(float* j)
    {
        (*j)++;
    }
    
    void inc2(float& j)
    {
        j++;
    }
    
    int main()
    {
        double elapsed;
        double elapsed2;
        
        float j = 20;
        float *p = &j;
        float x = 20;
        int i;
        
        clock_t start = clock();
        for (i = 0; i < 100000000; i++)
        {
            inc(p);
        }
        clock_t stop = clock();
        elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
        printf("*(pointer) ms: %f", elapsed);
        printf("\n");
        
        clock_t start2 = clock();
        for (i = 0; i < 100000000; i++)
        {
            inc2(x);
        }
        clock_t stop2 = clock();
        elapsed2 = (double)(stop2 - start2) * 1000.0 / CLOCKS_PER_SEC;
        printf("&(address) ms: %f", elapsed2);
        
        return 0;    
    }
    Code:
    Output:-
    *(pointer) ms: 750.000000
    &(address) ms: 703.000000
    Address has it just, not worth bothering about the time.
    I will take the advice given.

    Regards

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,086
    Quote Originally Posted by mad-hatter
    Address has it just
    The concept in C++ terminology is "reference", not "address". The concept of "address" is equivalent to the concept of "pointer", e.g., taking the address of an object gives you a pointer to the object. In more general computer science terminology the "reference" concept also includes "pointer", hence the phrase "dereference a pointer", but C++ makes a distinction in terms because of difference in type.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Quote Originally Posted by laserlight View Post
    The concept in C++ terminology is "reference", not "address". The concept of "address" is equivalent to the concept of "pointer", e.g., taking the address of an object gives you a pointer to the object. In more general computer science terminology the "reference" concept also includes "pointer", hence the phrase "dereference a pointer", but C++ makes a distinction in terms because of difference in type.
    Yes. This is incredibly true and I had to learn it the hard way.

    In C++ references are awesome because they're never null and as such will always point to a validly constructed object.

    However, C++ is the outlier in this terminology. In most other languages, a reference is basically the same thing as a pointer. In Java, you can have null references. And in JavaScript, it's the exact same thing.

    This confused me a lot at first because I thought JS references were like C++ references when in all reality, JS references are pointers. Then my coding skills dramatically improved because I was like, "Oh, I'm just passing around a pointer."

    So yeah, C++ is the freak of the programming world with its weird but awesome implementation of references.

  10. #10
    Registered User
    Join Date
    May 2015
    Posts
    56
    Hello laserlight,

    Thanks.
    Quote Originally Posted by laserlight View Post
    The concept in C++ terminology is "reference", not "address".
    Regards

  11. #11
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Quote Originally Posted by MutantJohn View Post
    In C++ references are awesome because they're never null and as such will always point to a validly constructed object.
    Not always. Consider the following code:

    Code:
    void func()
    {
      int& rInt = *static_cast<int*>(nullptr);
    }
    Granted, this is a scenario that's relatively easy to avoid, but it's a real possibility.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  12. #12
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Quote Originally Posted by Elkvis View Post
    Not always. Consider the following code:

    Code:
    void func()
    {
      int& rInt = *static_cast<int*>(nullptr);
    }
    Granted, this is a scenario that's relatively easy to avoid, but it's a real possibility.
    Thanks for the correction!

    Oh man, I found out that you can by-pass template-based std::enable_if checks by passing in void as a template argument. Talk about crafty lol.

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Elkvis View Post
    Not always. Consider the following code:

    Code:
    void func()
    {
      int& rInt = *static_cast<int*>(nullptr);
    }
    Granted, this is a scenario that's relatively easy to avoid, but it's a real possibility.
    You can't dereference null. If this runs, it's undefined behaviour and nothing can save you from undefined behaviour. It can break anything, including references.
    I think it's a pretty safe argument that if you receive a reference, then it is not null.

    Quote Originally Posted by MutantJohn View Post
    I actually like Google's C++ style guide in this one respect. Arguments that are meant to be read from are references and arguments that are meant to be written to are pointers. I kind of like that for some reason.
    This seems awfully dumb to me. Arguments that are meant to be read should be const; arguments that are meant to be written to shall not be const. That makes the interface pretty clear to me.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Registered User
    Join Date
    Apr 2013
    Posts
    1,645
    Quote Originally Posted by MutantJohn View Post
    I actually like Google's C++ style guide in this one respect. Arguments that are meant to be read from are references and arguments that are meant to be written to are pointers. I kind of like that for some reason.
    One reason is when just looking at code that calls a function, you don't know if the function is using references and can modify the parameters unless you have looked at the function or it's prototype to see if it uses references. If the function uses pointers, then the calling code has to supply pointers (or references if you prefer that term) to parameters, so looking at the calling code will be enough to know if the called function could modify the parameters. You'd still need to look at the function to see if or when or which parameters may be modified.

  15. #15
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Quote Originally Posted by Elysia View Post
    You can't dereference null. If this runs, it's undefined behaviour and nothing can save you from undefined behaviour. It can break anything, including references.
    I think it's a pretty safe argument that if you receive a reference, then it is not null.
    It may be undefined behavior to explicitly dereference nullptr, but the point was to show that a reference derived from a pointer could still be invalid, and it's a real situation that a programmer might encounter.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing by reference of by value?
    By abd in forum C Programming
    Replies: 32
    Last Post: 01-28-2010, 04:49 PM
  2. passing by reference
    By mapunk in forum C Programming
    Replies: 2
    Last Post: 11-30-2005, 10:39 PM
  3. Passing by Reference
    By Davros in forum C++ Programming
    Replies: 9
    Last Post: 10-11-2004, 03:51 PM
  4. passing by address vs passing by reference
    By lambs4 in forum C++ Programming
    Replies: 16
    Last Post: 01-09-2003, 01:25 AM
  5. passing value or reference?
    By pari in forum C Programming
    Replies: 3
    Last Post: 11-22-2002, 12:33 PM

Tags for this Thread