Reference (C++)

From WikiMD's Wellness Encyclopedia

Reference (C++)[edit | edit source]

In computer programming, a reference in C++ is a simple reference datatype that is less powerful but safer than the pointer type inherited from C. The name C++ reference may cause confusion, as in computer science a reference is a general concept datatype, with semantics that differs from that of C++ references. Particularly, the C++ reference is designed to be used in function parameter lists and function return types to provide some of the utilities of pointers but without some of their drawbacks.

Overview[edit | edit source]

In C++, a reference is a type of variable that acts as an alias to another object or value. The reference itself is not an object (it has no identity; taking the address of a reference gives the address of the referent; and the same reference can refer to different objects over its lifetime), but it does refer to an object. References are particularly useful for pass-by-reference semantics in function calls.

Syntax and semantics[edit | edit source]

A reference is declared using the '&' operator, like so:

```c++ int x = 10; int& y = x; ```

In this example, 'y' is a reference to 'x'. Any changes made to 'y' will also affect 'x', and vice versa. This is because 'y' is not a new variable, but simply a different name for 'x'.

Use in function calls[edit | edit source]

One of the most common uses of references in C++ is in function calls. By declaring a function parameter as a reference, you can modify the original argument passed into the function. This is known as pass-by-reference. Here is an example:

```c++ void increment(int& x) {

   x++;

}

int main() {

   int a = 5;
   increment(a);
   // 'a' is now 6
   return 0;

} ```

In this example, the 'increment' function takes a reference to an integer as its parameter. When 'a' is passed into the function, the function is actually modifying 'a' itself, not a copy of 'a'.

See also[edit | edit source]


WikiMD
Navigation: Wellness - Encyclopedia - Health topics - Disease Index‏‎ - Drugs - World Directory - Gray's Anatomy - Keto diet - Recipes

Search WikiMD

Ad.Tired of being Overweight? Try W8MD's physician weight loss program.
Semaglutide (Ozempic / Wegovy and Tirzepatide (Mounjaro / Zepbound) available.
Advertise on WikiMD

WikiMD's Wellness Encyclopedia

Let Food Be Thy Medicine
Medicine Thy Food - Hippocrates

WikiMD is not a substitute for professional medical advice. See full disclaimer.
Credits:Most images are courtesy of Wikimedia commons, and templates Wikipedia, licensed under CC BY SA or similar.

Contributors: Prab R. Tumpati, MD