Tuesday, August 12, 2014

Function: Parameter as Reference or Pointer


void funcParameterAsReference(int& inputOrOutput)
{
    inputOutputVal = 5;
}

int myInt = 0;
funcReference(myInt);
OR
void funcParameterAsPointer(int* inputOrOutput)
{
    *inputOutputVal = 5;
}

int myInt = 0;
funcPointer(&myInt);
My rule of thumb is:
Use pointers if you want to do arithmetic with them or if you ever have to pass a NULL-pointer. Use references otherwise. So for input parameter use const reference and for output parameter use plain reference.
As input parameter :
void func(const int& input);
As output parameter :
void func(int& Output);
Why should pass-by-reference be used instead of pass-by-pointer? The most obvious reason is that a reference cannot be null. In a function that takes a pointer, you have to check that the pointer is not null before you use it, at least with a debug assertion. During a proper code review you have to analyze more code to be sure that you don't accidentally pass a null pointer to a function that doesn't expect one. I've found that it takes much longer to review functions that take pointer arguments for this very reason; it's so much easier to get it wrong when using pointers.
One advantage of using pointer as a parameter is when you have to add a new parameter to an existing function (for whatever reason). This way you can pass NULL to it, if it doesn't use the parameter in the implementation (definition)
void myFunc1(int* inp);
void myFunc2(int* inp);

int main()
{
    int inp = 0;
    myFunc1(&inp); // You can't pass NULL to myFunc1 because it uses inp in the implementation. If NULL is passed, 
                   // it will crash. 
                   // e.g. 
                   // int* inp = NULL;
                   // myFunc1(inp);
                   // OR
                   // myFunc1(NULL);

    cout << "inp = " << inp << endl;
    
    myFunc2(NULL); // You can pass NULL to myFunc2 because it doesn't use inp in the implementation

    system("PAUSE");
    return 0;
}

void myFunc1(int* inp)
{
    *inp = 99;
    cout << "I am in myFunc1" << endl;
}

void myFunc2(int* inp)  
{  
    cout << "I am in myFunc2" << endl;  
}  
Ref: http://stackoverflow.com/questions/4028413/out-parameters-and-pass-by-reference

No comments:

Post a Comment