Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Reference Use Cases | References Fundamentals
C++ Pointers and References

book
Reference Use Cases

References provide a powerful mechanism for working with functions. Similar to pointers they enable a direct connection between the caller and the called function, allowing for efficient parameter passing and modification of variables.

Pass-by-reference

This involves passing the actual reference to the variable rather than its value. This allows functions to directly manipulate the original variables.

main.cpp

main.cpp

copy
#include <iostream>

void increment(int* num) { (*num)++; }

int main()
{
int num = 5;
int* p_num = &num;

increment(p_num);
std::cout << "Original value: " << num << std::endl;
}
12345678910111213
#include <iostream> void increment(int* num) { (*num)++; } int main() { int num = 5; int* p_num = &num; increment(p_num); std::cout << "Original value: " << num << std::endl; }

Everything functions properly, but failing to assign an address to the pointer or passing a nullptr to the function could result in errors.

main.cpp

main.cpp

copy
#include <iostream>

void increment(int& num) { num++; }

int main()
{
int num = 5;
increment(num);
std::cout << "Original value: " << num << std::endl;
}
12345678910
#include <iostream> void increment(int& num) { num++; } int main() { int num = 5; increment(num); std::cout << "Original value: " << num << std::endl; }

Reference Variable as Alias

A reference is like a nickname for a variable. It lets you access the variable using a simpler name, making your code easier to understand, while also avoiding unnecessary memory overhead.

main.cpp

main.cpp

copy
#include <iostream>

int main()
{
float temperature_outside = 67.2;
const float& thermostat = temperature_outside;
temperature_outside += 15.7;

std::cout << thermostat << std::endl;
std::cout << temperature_outside << std::endl;
}
123456789101112
#include <iostream> int main() { float temperature_outside = 67.2; const float& thermostat = temperature_outside; temperature_outside += 15.7; std::cout << thermostat << std::endl; std::cout << temperature_outside << std::endl; }

Any modifications made to the temperature_outside variable will be reflected in the thermostat reference. However, attempts to alter the value through the thermostat reference itself are restricted due to the use of the const qualifier.

This approach provides a secure method for retrieving temperature readings using the thermostat reference while retaining the ability to update the temperature_outside variable.

question mark

What is the purpose of a reference in C++?

Select the correct answer

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 3. Hoofdstuk 2

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

some-alt