Comparing pass-by-value and pass-by-reference with references. - C++ Function

C++ examples for Function:Function Parameter

Description

Comparing pass-by-value and pass-by-reference with references.

Demo Code

#include <iostream>

int squareByValue(int);
void squareByReference(int &);

int main(int argc, const char *argv[]) {
    int x = 2;/*w w w.jav a 2 s  .  co  m*/
    int z = 4;

    // demonstrate squareByValue
    std::cout << "x = " << x << " before squareByValue\n";
    std::cout << "Value returned by squareByValue: " << squareByValue(x)<< std::endl;
    std::cout << "x = " << x << " after squareByValue\n" << std::endl;

    // demonstrate squareByReference
    std::cout << "z = " << z << " before squareByReference\n";
    squareByReference(z);
    std::cout << "z = " << z << " after squareByReference\n";

    return 0;
}
int squareByValue(int number) { 
   return number *= number; 
}

void squareByReference(int &numberRef) { 
   numberRef *= numberRef; 
}

Result


Related Tutorials