Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: difference between ampersand "&" and asterisk "*" in function/method declaration?

Is there some kind of subtle difference between those:

void a1(float &b) {     b=1; }; a1(b); 

and

void a1(float *b) {     (*b)=1; }; a1(&b); 

?

They both do the same (or so it seems from main() ), but the first one is obviously shorter, however most of the code I see uses second notation. Is there a difference? Maybe in case it's some object instead of float?

like image 798
Slava V Avatar asked Feb 27 '09 20:02

Slava V


People also ask

What is difference between & and * in C?

* can be either the dereference operator or part of the pointer declaration syntax. & can be either the address-of operator or (in C++) part of the reference declaration syntax.

What does ampersand mean in C?

The ampersand is the address of operator. It returns the memory location of a variable and that's the only way it's used, prefixed to a variable like the engine on a train. The variable doesn't even have to be initialized, just declared.

Why we use double ampersand in C?

In programming, a double ampersand is used to represent the Boolean AND operator such as in the C statement, if (x >= 100 && x >= 199).

What is the difference between asterisk and ampersand in C?

The & is a unary operator in C which returns the memory address of the passed operand. This is also known as address of operator. <> The * is a unary operator which returns the value of object pointed by a pointer variable. It is known as value of operator.


2 Answers

Yes. The * notation says that what's being pass on the stack is a pointer, ie, address of something. The & says it's a reference. The effect is similar but not identical:

Let's take two cases:

   void examP(int* ip);    void examR(int& i);     int i; 

If I call examP, I write

   examP(&i); 

which takes the address of the item and passes it on the stack. If I call examR,

   examR(i); 

I don't need it; now the compiler "somehow" passes a reference -- which practically means it gets and passes the address of i. On the code side, then

   void examP(int* ip){         *ip += 1;    } 

I have to make sure to dereference the pointer. ip += 1 does something very different.

   void examR(int& i){         i += 1;    } 

always updates the value of i.

For more to think about, read up on "call by reference" versus "call by value". The & notion gives C++ call by reference.

like image 24
Charlie Martin Avatar answered Sep 28 '22 17:09

Charlie Martin


Both do the same, but one uses references and one uses pointers.

See my answer here for a comprehensive list of all the differences.

like image 108
Brian R. Bondy Avatar answered Sep 28 '22 16:09

Brian R. Bondy