Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `*&` in a function declaration mean?

Tags:

I wrote a function along the lines of this:

void myFunc(myStruct *&out) {     out = new myStruct;     out->field1 = 1;     out->field2 = 2; } 

Now in a calling function, I might write something like this:

myStruct *data; myFunc(data); 

which will fill all the fields in data. If I omit the '&' in the declaration, this will not work. (Or rather, it will work only locally in the function but won't change anything in the caller)

Could someone explain to me what this '*&' actually does? It looks weird and I just can't make much sense of it.

like image 336
bastibe Avatar asked Sep 15 '09 12:09

bastibe


People also ask

What is mean @?

On the Internet, @ (pronounced "at" or "at sign" or "address sign") is the symbol in an E-mail address that separates the name of the user from the user's Internet address, as in this hypothetical e-mail address example: [email protected].

What does := means in math?

:= (the equal by definition sign) means “is equal by definition to”. This is a common alternate. form of the symbol “=Def”, which appears in the 1894 book Logica Matematica by the logician. Cesare Burali-Forti (1861–1931).

What does ∧ mean in math?

∧ is (most often) the mathematical symbol for logical conjunction, which is equivalent to the AND operator you're used to. Similarly ∨ is (most often) logical disjunction, which would be equivalent to the OR operator.


2 Answers

The & symbol in a C++ variable declaration means it's a reference.

It happens to be a reference to a pointer, which explains the semantics you're seeing; the called function can change the pointer in the calling context, since it has a reference to it.

So, to reiterate, the "operative symbol" here is not *&, that combination in itself doesn't mean a whole lot. The * is part of the type myStruct *, i.e. "pointer to myStruct", and the & makes it a reference, so you'd read it as "out is a reference to a pointer to myStruct".

The original programmer could have helped, in my opinion, by writing it as:

void myFunc(myStruct * &out) 

or even (not my personal style, but of course still valid):

void myFunc(myStruct* &out) 

Of course, there are many other opinions about style. :)

like image 171
unwind Avatar answered Oct 18 '22 07:10

unwind


In C and C++, & means call by reference; you allow the function to change the variable. In this case your variable is a pointer to myStruct type. In this case the function allocates a new memory block and assigns this to your pointer 'data'.

In the past (say K&R) this had to be done by passing a pointer, in this case a pointer-to-pointer or **. The reference operator allows for more readable code, and stronger type checking.

like image 30
Adriaan Avatar answered Oct 18 '22 08:10

Adriaan