Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ tie one variable to two others via references

In C++, we can define a variable by reference like:

int foo = 3;
int &bar = foo;

Then, the following code

cout << foo << " " << bar;

will print

3 3

because the "value" of bar is tied to the value of foo by reference(&). I'm wondering, is there a way to tie the value of "bar" to two variables? Say I have three variables: geddy, neil, and alex, and I want neil to always equal alex + geddy. Is there a way two write something like:

int alex = 4;
int geddy = 5;
int &neil = alex + geddy;

So that neil will return 9? Then, if I change alex to 7, neil will return 12?

like image 306
awwsmm Avatar asked Apr 30 '16 01:04

awwsmm


People also ask

How can you pass a variable by reference?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.

Can two variables have the same address in C?

Not in C. In C++ you could do it with references. In C, a variable is by definition a unique address.

What does it mean for a variable to be referenced?

A reference variable is a variable that points to an object of a given class, letting you access the value of an object. An object is a compound data structure that holds values that you can manipulate. A reference variable does not store its own values.

What happens when you assign a reference to a variable?

A reference assignment statement redirects either a reference variable or an array variable. A reference variable is a pointer to an object. An array variable points to a set of reference variables, which points to a set of objects.


1 Answers

No, not really. You could make a function or functor though:

int alex = 4;
int geddy = 5;

auto neil = [&]() { return alex + geddy; };
std::cout << neil() << "\n";
like image 176
Bill Lynch Avatar answered Sep 20 '22 20:09

Bill Lynch