25.09.2017 Views

cpp_tutorial

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

C++<br />

int temp;<br />

temp = x; /* save the value at address x */<br />

x = y; /* put y into x */<br />

y = temp; /* put x into y */<br />

}<br />

return;<br />

When the above code is compiled and executed, it produces the following result:<br />

Before swap, value of a :100<br />

Before swap, value of b :200<br />

After swap, value of a :200<br />

After swap, value of b :100<br />

Reference as Return Value<br />

A C++ program can be made easier to read and maintain by using references<br />

rather than pointers. A C++ function can return a reference in a similar way as it<br />

returns a pointer.<br />

When a function returns a reference, it returns an implicit pointer to its return<br />

value. This way, a function can be used on the left side of an assignment<br />

statement. For example, consider this simple program:<br />

#include <br />

#include <br />

using namespace std;<br />

double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};<br />

double& setValues( int i )<br />

{<br />

return vals[i]; // return a reference to the ith element<br />

}<br />

// main function to call above defined function.<br />

int main ()<br />

138

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!