Search code examples
c++functionreferencereturnpass-by-reference

Passing argument by reference; does the function return type HAVE to be void?


I've recently started to learn C++ and now I'm learning about passing arguments to functions. Knowing there are two methods of doing so, I've made a simple code of doubling a number given by the user.

My first question is, When passing an argument to a function through reference, MUST that function be a void type or can it be an int too?

I ask this question because most of the examples I've seen have been using void.

Second question is my code,


    #include <iostream>


    //using std::cout;
    //using std::cin;
    //using std::endl;


    using namespace std;


    int doubleByValue(int value){       //this is the function which takes the argumrnt passed down by main as a Value
        int Doubled;
        Doubled = value * value;

        return Doubled;
    }

    /*
    int doubleByReference(int &value){      //This is the function which takes the argument passed from main as a Reference
        value = value * value;

        return value;
    }
    */

    void doubleByReference(int &value){     //This is the function which takes the argument passed from main as a Reference
        value = value * value;

    }


    int main(){
        cout << "In this program we would be doubling the values entered by the user" << endl;
        cout << "using the two methods of passing arguments, through value and by reference." << endl;


        int Number = 0;
        cout << "Please enter a Number: ";
        cin >> Number;


        cout << endl << "Number doubled after passed by Value: " << doubleByValue(Number) << endl;
        cout << endl << "Number doubled after passed by Reference: " << doubleByReference(Number) << endl;

        return 0;
    }

My top method, i.e the passing an argument through value method works completely fine.

But, I've used two methods to pass an argument by reference, by which the type int function works completely fine (This is the one I've commented) but I get a ton of errors or warnings for the second one. Why is that happening? because there's not much of a difference between the two I really don't understand how could there be such big errors or warnings for this.

I notice the program still runs so I'm guessing it's just warnings.


Solution

  • Parameters of a function and the return type are not related.

    The warnings you get come from std::cout .... << doubleByReference(value), because std::cout expects a value, but that function returns nothing.