Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function parameters: use a reference or a pointer (and then dereference)?

I was given some code in which some of the parameters are pointers, and then the pointers are dereferenced to provide values. I was concerned that the pointer dereferencing would cost cycles, but after looking at a previous StackOverflow article: How expensive is it to dereference a pointer?, perhaps it doesn't matter.

Here are some examples:


bool MyFunc1(int * val1, int * val2)
{
    *val1 = 5;
    *val2 = 10;
    return true;
}

bool MyFunc2(int &val1, int &val2)
{
    val1 = 5;
    val2 = 10;
    return true;
}

I personally prefer the pass-by-reference as a matter of style, but is one version better (in terms of process cycles) than another?

like image 439
Jenner Avatar asked Oct 30 '09 16:10

Jenner


People also ask

What is referencing and dereferencing pointer in C?

I read about * referencing operator and & dereferencing operator; or that referencing means making a pointer point to a variable and dereferencing is accessing the value of the variable that the pointer points to.

Why are pointers used in passing parameters by reference?

Passing by pointer Vs Passing by Reference in C++ Only difference is that References are used to refer an existing variable in another name whereas pointers are used to store address of variable. It is safe to use reference because it cannot be NULL.

When should you use a pointer and when should you use a reference?

Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don't need "reseating". This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.

Can you dereference a function pointer?

As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments just as in a normal function call.


1 Answers

My rule of thumb is to pass by pointer if the parameter can be NULL, ie optional in the cases above, and reference if the parameter should never be NULL.

like image 93
dma Avatar answered Oct 08 '22 14:10

dma