References

References - One way of viewing references is to consider...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
References In the last newsletter we discussed using function prototypes in C++ to eliminate a common type of error encountered in C, that of calling a function with the wrong number or types of arguments. Another C++ feature that can be used to reduce programming errors is known as references. A reference is another name for an object. For example, in this code: int i; int& ir = i; ir is another name for i. To see how references are useful, and also how they're implemented, consider writing a function that has two return values to pass back. In ANSI C, we might say: void f(int a, int b, int* sum, int* prod) { *sum = a + b; *prod = a * b; } void g() { int s; int p; f(37, 47, &s, &p); } In C++, we would say: { sum = a + b; prod = a * b; } void g() { int s; int p; f(37, 47, s, p); }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: One way of viewing references is to consider that they have some similarities to C pointers, but with one level of pointer removed. Pointers are a frequent source of errors in C. A reference must be initialized, and its value (the pointed at object) cannot be changed after initialization. The value of the reference cannot change, but the value of the referenced object can, unless the reference is declared as const. So, for example: int i = 0; int& ir = i; ir = -19; // i gets the value -19 is acceptable, while: const int& irc = 47; irc = -37; // error is not. A constant reference that points at a value like 47 can be implemented using a temporary. References are useful in argument passing and return. Another use is illustrated below in the section on writing robust code....
View Full Document

Page1 / 2

References - One way of viewing references is to consider...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online