Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ * vs & in function declaration [duplicate]

Possible Duplicate:
Difference between pointer variable and reference variable in C++

When should I declare my variables as pointers vs objects passed-by-reference? They compile to the same thing in assembly (at least run-time asymptotically) so when should I use which?

void foo(obj* param)
void foo(obj& param)
like image 874
Paul Tarjan Avatar asked Jul 04 '09 08:07

Paul Tarjan


People also ask

What is the difference between * and & 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.

Which one is better C or C++?

Compared to C, C++ has significantly more libraries and functions to use. If you're working with complex software, C++ is a better fit because you have more libraries to rely on. Thinking practically, having knowledge of C++ is often a requirement for a variety of programming roles.

Which is harder C or C++?

Ease of Coding As an extension of C, C++ allows for highly controlled object-oriented code. Simply, if C is easy, then C++ is easier.


2 Answers

My rule is simple: use * when you want to show that value is optional and thus can be 0.

Excluding from the rule: all the _obj_s around are stored in containers and you don't want to make your code look ugly by using everywhere foo(*value); instead of foo(value); So then to show that value can't be 0 put assert(value); at the function begin.

like image 175
Mykola Golubyev Avatar answered Nov 07 '22 01:11

Mykola Golubyev


I follow the Google style guide standard as it makes the most sense to me. It states:

Within function parameter lists all references must be const:

void Foo(const string &in, string *out);

In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers. Input parameters may be const pointers, but we never allow non-const reference parameters.

One case when you might want an input parameter to be a const pointer is if you want to emphasize that the argument is not copied, so it must exist for the lifetime of the object; it is usually best to document this in comments as well. STL adapters such as bind2nd and mem_fun do not permit reference parameters, so you must declare functions with pointer parameters in these cases, too.

like image 42
MahlerFive Avatar answered Nov 07 '22 02:11

MahlerFive