c++parametersreferenceconstants

What is the difference between a const reference and normal parameter?


void DoWork(int n);
void DoWork(const int &n);

What's the difference?


Solution

  • The difference is more prominent when you are passing a big struct/class:

    struct MyData {
        int a,b,c,d,e,f,g,h;
        long array[1234];
    };
    void DoWork(MyData md);
    void DoWork(const MyData& md);
    

    When you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. If you are using const reference, you pass it by reference and the original data is not copied.

    In both cases, the original data cannot be modified from inside the function.


    EDIT:
    In certain cases, the original data might be able to get modified as pointed out by Charles Bailey in his answer.