Just as pointers, references can be used as parameters.
Our function will demand one reference in this example. A job will be to multiply original value with itself
void doubleUsingRef(int &xRef) {
cout << "Address Right Now: " << &xRef << endl;
xRef = xRef * xRef;
}
Inside main() section first we are establishing a variable:
int some_number = 10;
Than printing of memory address and a value:
cout << "Address BEFORE Operations: " << &some_number << endl;
cout << "Value BEFORE Operations: " << some_number << endl;
Now we are using our function previously created:
doubleUsingRef(some_number);
And this is final value:
cout << "Value AFTER Operations: " << some_number << endl;
Full source:
#include <iostream>
using namespace std;
void doubleUsingRef(int &xRef);
int main() {
int some_number = 10;
cout << "Address BEFORE Operations: " << &some_number << endl;
cout << "Value BEFORE Operations: " << some_number << endl;
doubleUsingRef(some_number);
cout << "Value AFTER Operations: " << some_number << endl;
return 0;
}
void doubleUsingRef(int &xRef) {
cout << "Address Right Now: " << &xRef << endl;
xRef = xRef * xRef;
}
Result:
Address BEFORE Operations: 0x6dfeec
Value BEFORE Operations: 10
Address Right Now: 0x6dfeec
Value AFTER Operations: 100
Process returned 0 (0x0) execution time : 0.060 s
Press any key to continue.
No comments:
Post a Comment