Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between & and * as a parameter

Tags:

c++

What is the difference between the following two parameter types? The first accepts a pointer, which is in effect a memory address, and the second is also a memory address?

foo(float& bar)
{
    // do stuff
}

foo(float* bar)
{
    // do stuff
}

Could you not call both with:

float pow = 3.0f;

foo(&pow);

or

float* pow = 3.0f;

foo(pow);
like image 227
Dollarslice Avatar asked Dec 06 '22 19:12

Dollarslice


1 Answers

  • A pointer can be NULL, while a reference can't. This can be useful if you need to pass a NULL object for whatever reason.

  • With the pointer syntax, you pass a pointer when you call the function. With references, you just pass the variable:

    refer(float& bar) {}
    point(float* bar) {}
    
    float afloat = 1.0f;
    
    refer(afloat);
    point(&afloat);
    

    This means with the pointer syntax you have to pass a pointer when you call the function. With the reference syntax, you don't know if the function takes it by reference or by value without looking at the function definition.

  • With the reference syntax you don't have to dereference the pointer in your function, and work with it more naturally in your // do stuff section.

    foo(float& bar)
    {
        bar = 3.0f;
    } 
    
    // versus
    
    foo(float* bar)
    {
        *bar = 3.0f;
    }
    
like image 97
Aillyn Avatar answered Dec 22 '22 00:12

Aillyn