C++ Variables


It is possible to make one variable be another:

#include <iostream.h>

void main ()
{
double a = 3.1415927;

double &b = a; // b IS a

b = 89;

cout << "a contains: " << a << endl; // Displays 89.
}

(If you are used at pointers and absolutely want to know what happens,
simply think double &b = a is translated to double *b = &a and all
subsequent b are replaced by *b.) The value of REFERENCE b cannot be
changed afther its declaration. For example you cannot write, a few
lines further, &b = c expecting now b IS c. It won't work. Everything
is said on the declaration line of b. Reference b and variable a are
married on that line and nothing will separate them.

References can be used to allow a function to modify a calling variable:

#include <iostream.h>

void change (double &r, double s)
{
r = 100;
s = 200;
}

void main ()
{
double k, m;

k = 3;
m = 4;

change (k, m);

cout << k << ", " << m << endl; // Displays 100, 4.
}

If you are used at pointers in C and wonder how exactly
the program above works, here is how the C++ compiler translates
it (those who are not used at pointers, please skip this ugly piece of code):

#include <iostream.h>

void change (double *r, double s)
{
*r = 100;
s = 200;
}

void main ()
{
double k, m;

k = 3;
m = 4;

change (&k, m);

cout << k << ", " << m << endl; // Displays 100, 4.
}


A reference can be used to let a function return a variable:

#include <iostream.h>

double &biggest (double &r, double &s)
{
if (r > s) return r;
else return s;
}

void main ()
{
double k = 3;
double m = 7;

cout << "k: " << k << endl;
cout << "m: " << m << endl;
cout << endl;

biggest (k, m) = 10;

cout << "k: " << k << endl;
cout << "m: " << m << endl;
cout << endl;

biggest (k, m) ++;

cout << "k: " << k << endl;
cout << "m: " << m << endl;
cout << endl;
}


Again, provided you're used at pointer arithmetics and if you wonder how
the program above works, just think the compiler translated it into the
following standard C program:

#include <iostream.h>

double *biggest (double *r, double *r)
{
if (*r > *s) return r;
else return s;
}

void main ()
{
double k = 3;
double m = 7;

cout << "k: " << k << endl;
cout << "m: " << m << endl;
cout << endl;

(*(biggest (&k, &m))) = 10;

cout << "k: " << k << endl;
cout << "m: " << m << endl;
cout << endl;

(*(biggest (&k, &m))) ++;

cout << "k: " << k << endl;
cout << "m: " << m << endl;
cout << endl;
}


To end with, for people who have to deal
with pointers yet do not like it, references are very useful to un-pointer
variables:

#include <iostream.h>

double *silly_function () // This function returns a pointer to a double
{
static double r = 342;
return &r;
}

void main()
{
double *a;

a = silly_function();

double &b = *a; // Now b IS the double towards which a points!

b += 1; // Great!
b = b * b; // No need to write *a everywhere!
b += 4;

cout << "Content of *a, b, r: " << b << endl;




Added on July 4, 2007 Comment
}