How can I make a variable always equal to the result of some calculations?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







42















In math, if z = x+y/2, then z will always change whenever we replace the value of x and y. Can we do that in programming without having to specifically updating z whenever we change the value of x and y?



I mean something like that won't work, right?



int x;
int y;
int z{x + y};
cin >> x;
cin >> y;
cout << z;


If you're confused why I would need that, I want the variable shown live, and get it updated automatically when a rhs-variable make changes.



Like when killing a creep and get gold, then the net-worth (cash+worth of own items) shown changes. Or the speed meter of a car changing depending on how slow or fast you're driving.










share|improve this question




















  • 4





    Right, that won't work. That's a spreadsheet thing.

    – Pete Becker
    Mar 28 at 17:22






  • 3





    @RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

    – Michael D. Blake
    Mar 28 at 17:32






  • 23





    @NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

    – Onyz
    Mar 28 at 18:35






  • 46





    That's called a "function."

    – ApproachingDarknessFish
    Mar 28 at 22:58






  • 5





    Surely this is a bit of an XY-problem?

    – Carmeister
    Mar 29 at 18:25


















42















In math, if z = x+y/2, then z will always change whenever we replace the value of x and y. Can we do that in programming without having to specifically updating z whenever we change the value of x and y?



I mean something like that won't work, right?



int x;
int y;
int z{x + y};
cin >> x;
cin >> y;
cout << z;


If you're confused why I would need that, I want the variable shown live, and get it updated automatically when a rhs-variable make changes.



Like when killing a creep and get gold, then the net-worth (cash+worth of own items) shown changes. Or the speed meter of a car changing depending on how slow or fast you're driving.










share|improve this question




















  • 4





    Right, that won't work. That's a spreadsheet thing.

    – Pete Becker
    Mar 28 at 17:22






  • 3





    @RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

    – Michael D. Blake
    Mar 28 at 17:32






  • 23





    @NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

    – Onyz
    Mar 28 at 18:35






  • 46





    That's called a "function."

    – ApproachingDarknessFish
    Mar 28 at 22:58






  • 5





    Surely this is a bit of an XY-problem?

    – Carmeister
    Mar 29 at 18:25














42












42








42


6






In math, if z = x+y/2, then z will always change whenever we replace the value of x and y. Can we do that in programming without having to specifically updating z whenever we change the value of x and y?



I mean something like that won't work, right?



int x;
int y;
int z{x + y};
cin >> x;
cin >> y;
cout << z;


If you're confused why I would need that, I want the variable shown live, and get it updated automatically when a rhs-variable make changes.



Like when killing a creep and get gold, then the net-worth (cash+worth of own items) shown changes. Or the speed meter of a car changing depending on how slow or fast you're driving.










share|improve this question
















In math, if z = x+y/2, then z will always change whenever we replace the value of x and y. Can we do that in programming without having to specifically updating z whenever we change the value of x and y?



I mean something like that won't work, right?



int x;
int y;
int z{x + y};
cin >> x;
cin >> y;
cout << z;


If you're confused why I would need that, I want the variable shown live, and get it updated automatically when a rhs-variable make changes.



Like when killing a creep and get gold, then the net-worth (cash+worth of own items) shown changes. Or the speed meter of a car changing depending on how slow or fast you're driving.







c++ c++11






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 31 at 16:33







Michael D. Blake

















asked Mar 28 at 16:39









Michael D. BlakeMichael D. Blake

342313




342313








  • 4





    Right, that won't work. That's a spreadsheet thing.

    – Pete Becker
    Mar 28 at 17:22






  • 3





    @RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

    – Michael D. Blake
    Mar 28 at 17:32






  • 23





    @NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

    – Onyz
    Mar 28 at 18:35






  • 46





    That's called a "function."

    – ApproachingDarknessFish
    Mar 28 at 22:58






  • 5





    Surely this is a bit of an XY-problem?

    – Carmeister
    Mar 29 at 18:25














  • 4





    Right, that won't work. That's a spreadsheet thing.

    – Pete Becker
    Mar 28 at 17:22






  • 3





    @RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

    – Michael D. Blake
    Mar 28 at 17:32






  • 23





    @NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

    – Onyz
    Mar 28 at 18:35






  • 46





    That's called a "function."

    – ApproachingDarknessFish
    Mar 28 at 22:58






  • 5





    Surely this is a bit of an XY-problem?

    – Carmeister
    Mar 29 at 18:25








4




4





Right, that won't work. That's a spreadsheet thing.

– Pete Becker
Mar 28 at 17:22





Right, that won't work. That's a spreadsheet thing.

– Pete Becker
Mar 28 at 17:22




3




3





@RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

– Michael D. Blake
Mar 28 at 17:32





@RobertAndrzejuk Because it'd be very useful. For example, if you write a game and have something like networth(cash+the worth of all you own). You will have to call the function of networth everytime one of those update. That would be very annoying and error prone if you forgot to call the function somewhere.

– Michael D. Blake
Mar 28 at 17:32




23




23





@NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

– Onyz
Mar 28 at 18:35





@NayWunnaZaw In my experience this is why getters and setters are encouraged over direct variable access. If you always wanted networth to be updated, you could retrieve the value using getNetWorth() which would itself call updateNetWorth() before returning the value... or just calculate it before returning it.

– Onyz
Mar 28 at 18:35




46




46





That's called a "function."

– ApproachingDarknessFish
Mar 28 at 22:58





That's called a "function."

– ApproachingDarknessFish
Mar 28 at 22:58




5




5





Surely this is a bit of an XY-problem?

– Carmeister
Mar 29 at 18:25





Surely this is a bit of an XY-problem?

– Carmeister
Mar 29 at 18:25












12 Answers
12






active

oldest

votes


















43














Edit: While I fully answered the question as asked, please have a look at Artelius' answer, too. It addresses some issues my answer doesn't (encapsulation, avoidance of redundancies, risks of dangling references). A possible optimisation, if calculation is expensive, is shown in Jonathan Mee's answer.





You mean something like this:



class Z
{
int& x;
int& y;
public:
Z(int& x, int& y) : x(x), y(y) { }
operator int() { return x + y; }
};


The class delays calculation of the result until casted as int. As cast operator is not explicit, Z can be used whenever an int is required. As there's an overload of operator<< for int, you can use it with e. g. std::cout directly:



int x, y;
Z z(x, y);
std::cin >> x >> y;
if(std::cin) // otherwise, IO error! (e. g. bad user input)
std::cout << z << std::endl;


Be aware, though, that there's still a function call (the implicit one of the cast operator), even though it is not visible. And actually the operator does some true calculations (rather than just accessing an internal member), so it is questionable if hiding away the function call really is a good idea...






share|improve this answer


























  • while this could work whenever we need z, this requires a whole class to be created only for one variable. so i'm preferring the lambda method to be chosen as answer.

    – Michael D. Blake
    Mar 29 at 14:42






  • 5





    @NayWunnaZaw: If it's a one-off usage, sure, use the lambda. But if your code has multiple places where dynamic types like this are needed, a slightly more complex class (templated, receiving a function, e.g. one of the operator wrappers like std::plus) would be only a little longer at time of definition, while supporting reuse without redefining a fairly subtle thing at each point of use. I think this is the better answer for when this is a pattern, not merely a one-off trick.

    – ShadowRanger
    Mar 29 at 16:43











  • @ShadowRanger Yes, I understand that. But it'd be off topic if I accept the class type answer. What I asked is a variable which will get updated whenever x and y are changed. So I think lambda is an appropriate answer for my question.

    – Michael D. Blake
    Mar 29 at 18:21






  • 5





    @NayWunnaZaw: BTW, just to be clear: You realize lambdas are (unnamed) classes, right? They're syntactic sugar around functors (the captures are instance attributes, and the arguments are arguments to operator()) so in both cases a class exists (or doesn't exist due to inlining). This explicitly overrides operator int (so implicit conversion does the trick), where lambdas implicitly override operator() (so explicit call parens are needed), otherwise they're the same. It's fine if you prefer the lambda for code brevity, but in terms of what actually runs, both of them involve classes.

    – ShadowRanger
    Mar 29 at 19:16








  • 1





    @MichaelD.Blake Actually, that's use case dependent. What's fine in one application can turn out to be inefficient in another one...

    – Aconcagua
    Apr 1 at 19:02



















43














You can get close to this with by using a lambda in C++. Generally, when you set a variable like



int x;
int y;
int z{x + y};


z will only be the result of x + y at that time. You'd have to do z = x + y; every time you change x or y to keep it update.



If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like



int x;
int y;
auto z = [&](){ return x + y; };
cin >> x;
cin >> y;
cout << z();


and now z() will have the correct value instead of the uninitialized garbage that the original code had.



If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like



auto z = [&](){ static auto cache_x = x; 
static auto cache_y = y;
static auto cache_result = x + y;
if (x != cache_x || y != cache_y)
{
cache_x = x;
cache_y = y;
cache_result = x + y;
}
return cache_result;
};





share|improve this answer





















  • 2





    Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

    – Max Langhof
    Mar 28 at 17:03






  • 7





    And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

    – Mooing Duck
    Mar 28 at 22:25











  • @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

    – Fabio Turati
    Mar 28 at 23:34











  • @FabioTurati See Aconcagua's answer

    – NathanOliver
    Mar 28 at 23:48






  • 7





    Erm you probably don't want static for caching... lambdas can be stateful for a reason.

    – Mehrdad
    Mar 29 at 6:47





















21














The closest you probably can get is to create a functor:



#include <iostream>

int main() {
int x;
int y;

auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y

while(true) {
std::cin >> x;
std::cin >> y;
std::cout << z() << "n";
}
}





share|improve this answer































    18














    There are two chief techniques:




    1. Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type (as in Aconcagua's answer).


    2. Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).



    The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.






    share|improve this answer





















    • 1





      The observation approach is interesting, too, if calculations to be done are expensive. Appropriately implemented, I consider it more elegant than the caching proposed by NathanOliver...

      – Aconcagua
      Mar 29 at 9:27






    • 4





      @Aconcagua, amend that to: if calculations to be done are expensive and reads are more frequent than updates. Otherwise, we need to add a way to avoid computing values that don't get used.

      – Toby Speight
      Mar 29 at 12:18



















    14














    This sounds like the XY problem (pun intended).



    From the sound of it, you are not really writing code according to good object oriented practices. I would advise you not to use the "tricks" other people have suggested, but to actually learn how to make better use of OO structure.



    Before I go into that, note that assignment is distinct from an equality relation. The = in C++ is assignment, which is not the same as the = in maths. There are some (but not many) programming languages that do support equality relations, but C++ is not one of them. The thing is, adding support for equality relations introduces a heap of new challenges, so it's not as simple as "why isn't it in C++ yet".



    Anyway, in this case, you should probably be encapsulating your related variables in a class. Then you can use methods to obtain the "up-to-date" information. For example:



    class Player {
    std::vector<int> inventory;
    int cash;
    public:
    int inventory_total();
    int net_worth();
    }

    //adds up total value of inventory
    int Player::inventory_total() {
    int total = 0;
    for(std::vector<int>::iterator it = inventory.begin(); it != inventory.end(); ++it) {
    total += *it;
    }
    return total;
    }

    //calculates net worth
    int Player::net_worth() {
    //we are using inventory_total() as if it were a variable that automatically
    //holds the sum of the inventory values
    return inventory_total() + cash;
    }


    ...


    //we are using net_worth() as if it were a variable that automatically
    //holds the sum of the cash and total holdings
    std::cout << player1.net_worth();


    I admit that adding this behaviour to a class is quite a bit more complicated than saying z = x + y, but it really is only a few extra lines of code.




    That would be very annoying and error prone if you forgot to call the function somewhere.




    In this case the object doesn't have a net_worth member variable, so you can't accidentally use it instead of calling the function.






    share|improve this answer


























    • can you give me the pros and cons of using lambdas vs this? which would be better practice?

      – Michael D. Blake
      Mar 29 at 13:33






    • 1





      Yes, this is the (real) answer I would expect. Unfortunately, there is FGITW (I think it is a real problem).

      – Peter Mortensen
      Mar 30 at 1:44











    • Maybe worth to mention: Such a separate net_worth variable would introduce redundancy. There's a parallel to DBMS: You try to avoid any kind of redundancies there, too – at first place, at least, later, they can get re-introduced to speed up specific frequently used requests – which leads back to answer: iterating over the vector all the time might turn out to be too costly, so we might end up in caching the sum in a variable (again). But that shouldn't enter the design right at the start, it's an optimisation that only should get introduced on need (after analysis/profiling).

      – Aconcagua
      Apr 4 at 6:19



















    7















    1. You create a function for that.

    2. You call the function with the appropriate arguments when you need the value.




    int z(int x, int y)
    {
    return (x + y);
    }


    int x;
    int y;

    // This does ot work
    // int z{x + y};

    cin >> x;
    cin >> y;
    cout << z(x, y);





    share|improve this answer



















    • 1





      yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

      – Michael D. Blake
      Mar 28 at 16:54











    • @NayWunnaZaw, yes, that is correct.

      – R Sahu
      Mar 28 at 16:55






    • 1





      @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

      – R Sahu
      Mar 28 at 16:57






    • 4





      @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

      – Aconcagua
      Mar 28 at 17:04



















    4














    You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:



    DEMO



    int main()
    {
    int x;
    int y;

    const auto z = [&x, &y](){ return x+y; };

    std::cin >> x; // 1
    std::cin >> y; // 2
    std::cout << z() << std::endl; // 3

    std::cin >> x; // 3
    std::cin >> y; // 4
    std::cout << z() << std::endl; // 7
    }





    share|improve this answer





















    • 2





      Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

      – Aconcagua
      Mar 28 at 16:53











    • @Aconcagua thx! you are right. I edited my answer.

      – Hiroki
      Mar 28 at 16:54













    • Why downvoted ? At least I posted my answer faster than Ted with my tested code. Hmm... :)

      – Hiroki
      Mar 29 at 9:30








    • 1





      Well, I didn't and wouldn't have considered the parentheses worth doing so either. If they were the reason – well, people tend to never come back to remove a DV even if the answer was fixed, so (I don't think there's a notification for either, so people might just not even recognise...)

      – Aconcagua
      Mar 29 at 9:44











    • @Aconcagua thx for your comment. Although I was downvoted after few hours later of my edition, I was relieved to hear your words.

      – Hiroki
      Mar 29 at 20:36



















    4














    So a big problem that I see with the lambda solutions provided is that z is calculated each time that it is inspected even if neither x nor y has changed. To get around this you really need to link these variables.
    I would suggest doing that via class:



    class foo {
    int x;
    int y;
    int z;
    void calculate() { z = (x + y) / 2; }
    friend istream& operator >>(istream& lhs, foo& rhs);
    public:
    void set_x(const int param) {
    x = param;
    calculate();
    }
    int get_x() const { return x; }
    void set_y(const int param) {
    y = param;
    calculate();
    }
    int get_y() const { return y; }
    int get_z() const { return z; }
    };

    istream& operator >>(istream& lhs, foo& rhs) {
    lhs >> rhs.x >> rhs.y;
    rhs.calculate();
    return lhs;
    }


    This will recalculate z each time x or y is set. This is a good solution if you access z frequently, and x and y are set infrequently. If x and y are set frequently or calculate is expensive you might consider:



    class foo {
    int x;
    int y;
    int z;
    bool dirty;
    void calculate() { z = (x + y) / 2; }
    friend istream& operator >>(istream& lhs, foo& rhs);
    public:
    void set_x(const int param) {
    x = param;
    dirty = true;
    }
    int get_x() const { return x; }
    void set_y(const int param) {
    y = param;
    dirty = true;
    }
    int get_y() const { return y; }
    int get_z() const {
    if(dirty) {
    calculate();
    }
    return z;
    }
    };

    istream& operator >>(istream& lhs, foo& rhs) {
    lhs >> rhs.x >> rhs.y;
    rhs.dirty = true;
    return lhs;
    }


    Note that I've included an extraction operator, so whichever you choose your code can turn into something as simple as:



    foo xyz;

    cin >> xyz;
    cout << xyz.get_z();





    share|improve this answer
























    • I don't quite understand how lambda work. But if you've played dota you'd know how gold in the game work. The way it is displayed all the time and adding 1 gold every split-second. I'm asking this question with that in mind. How do I implement that in c++?

      – Michael D. Blake
      Mar 29 at 18:47






    • 2





      @NayWunnaZaw I mean generally you're going to have a main class which calls the tick function on any class that needs live updating, passing in a time elapsed since last tick parameter. You'd probably have a player class instead of just the simple foo which would do loads of things. Like the player class's tick would need to update the damage of poison effects, calculate cooldown times, and also calculate gold. I recognize this is probably a gross over simplification. But I do think you're going to want to go with a class here.

      – Jonathan Mee
      Mar 29 at 18:58











    • thanks for that, but I like lambda answer more for it's simplicity for a variable. and that fits my question. And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there.

      – Michael D. Blake
      Mar 29 at 19:10











    • @MichaelD.Blake There are always lots of solutions to a problem; as the actual programmer you are always in the best place to make that decision. But I do have some concerns as the statement: "And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there." That's the point of the class... it only calculates when required. The lambda will calculate every time you call it... Which is potentially very wasteful... But both the class and the lambda are wasteful if you're only finding z once. Is that where you're at?

      – Jonathan Mee
      Apr 4 at 12:38



















    2














    You can get what you're asking for by using macros:



    {
    int x, y;
    #define z (x + y)
    /* use x, y, z */
    #undef z
    }


    The #undef is for a little sanity. For more sanity, don't use macros at all, and go with one of the other answers, and deal with the extra verbosity.



    Although a class with a custom operator int would work in a lot of cases ... hmm.






    share|improve this answer



















    • 1





      Although this could use an EXTREME CAUTION warning, I think it is worth mentioning. Sometimes quick'n'dirty is called for. I have used tricks like this to save time in programming competitions, or in mindless repetitive matrix calculations that would be a lot more verbose and/or bug-prone using any other approach.

      – Artelius
      Mar 29 at 7:13





















    2














    What you're describing is late binding, which a compiled language like C++ can do only with difficulty. In an interpreted language, all you need is the ability to set z to an unevaluated expression and delay binding of z's value until the calculation is needed, typically signaled by a call to a function that forces the evaluation such as eval in Lisp. In my Expert System's rules language, I have not only eval but noeval, which protects its argument from one level of evaluation. That provides granular control over the binding, with some sub-expressions being evaluated (bound) and others not, if desired. This is not applicable to your scenario, but it sets the scene in terms of the language landscape.






    share|improve this answer































      2














      You could write a class that encapsulates its state to update either when mutated or return the right result when requested :



      #include <iostream>

      template<typename T, typename U, typename V>
      class DynamicCalc
      {
      public:
      DynamicCalc(const T& func, const U& memberOne, const V& memberTwo) :
      _func(func)
      , _memberOne(memberOne)
      , _memberTwo(memberTwo)
      {

      }

      void SetMemberOne(const U& memberOne) { _memberOne = memberOne; }
      void SetMemberTwo(const U& memberTwo) { _memberTwo = memberTwo; }
      auto Retrieve() { return _func(_memberOne, _memberTwo); }

      U GetMemberOne() { return _memberOne; }
      V GetMemberTwo() { return _memberTwo; }

      private:
      T _func;

      U _memberOne;
      V _memberTwo;
      };

      int main() {

      auto func = (int x, int y) {
      return x + y;
      };
      DynamicCalc<decltype(func), int, int> c(func, 3, 5);

      c.SetMemberOne(5);
      std::cout << c.Retrieve();
      }


      In truth, if you're happy for the calculation to happen when the value is reuqested then the getters/setters are unnecessary.






      share|improve this answer

































        0














        Ok, let me at last write the right and only true answer to your stated question:



        You can't.



        You can't write z = x + y and then have all the code using z magically re-run whenever x or y changes.



        So what can be done?



        As mentioned in other answers, there are several patterns to express that you want changes of x and y to cause some updates, but in any case you need these updates to happen more or less explicitly.



        Depending on a use case, you may:





        • Have the value recomputed anyway at all times this matters. E.g. if you write a game and redraw the screen every frame, then likely just making sure that you don't accidentally keep the z value between the frames is enough. Be aware of when your value can change and when it can't. Whether you use a function, a lambda, a class method, or just repeat the expression, is mostly esthetical decision. If available, this is the best approach, because it is fully transparent.



          For instance, in racing game you'd likely update your current speed at the beginning of the new tick computation, and then use the updated value when computing your car's movement, when redrawing the speed indicator, when creating the motion blur, and so on. You don't need any magic and not even a function, you can just use a variable, because you know your speed won't change during one frame.



        • Call the update explicitly. Use it e.g. when you have a single widget you need to update. Downside is that you need to remember to call the update, which is somewhat brittle, but on the upside - it is dead simple. A middle ground is to have the update call integrated with a setter, making it kind of poor man's Observer implementation.


        • Use Observer pattern (see also signals and slots, this is one way of implementing Observer). Use it e.g. when you have many widgets to update, or you create them dynamically. Avoid using it when one of the above works, they are way simpler.


        • Use dedicated reactive programming library. As such stuff exists, I feel obliged to mention it. However, I honestly don't see any application where I would use it. It mostly seems like a complicated way to shoot your feet. The implicit updates are going to backfire, and you'll have to rewrite everything. Just don't, not in C++. What is important: while this approach is closest to "magically update everything", it would impose constraints on how you write your code, and eventually you'll get one of the above solutions, just more complicated.







        share|improve this answer


























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55402807%2fhow-can-i-make-a-variable-always-equal-to-the-result-of-some-calculations%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          12 Answers
          12






          active

          oldest

          votes








          12 Answers
          12






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          43














          Edit: While I fully answered the question as asked, please have a look at Artelius' answer, too. It addresses some issues my answer doesn't (encapsulation, avoidance of redundancies, risks of dangling references). A possible optimisation, if calculation is expensive, is shown in Jonathan Mee's answer.





          You mean something like this:



          class Z
          {
          int& x;
          int& y;
          public:
          Z(int& x, int& y) : x(x), y(y) { }
          operator int() { return x + y; }
          };


          The class delays calculation of the result until casted as int. As cast operator is not explicit, Z can be used whenever an int is required. As there's an overload of operator<< for int, you can use it with e. g. std::cout directly:



          int x, y;
          Z z(x, y);
          std::cin >> x >> y;
          if(std::cin) // otherwise, IO error! (e. g. bad user input)
          std::cout << z << std::endl;


          Be aware, though, that there's still a function call (the implicit one of the cast operator), even though it is not visible. And actually the operator does some true calculations (rather than just accessing an internal member), so it is questionable if hiding away the function call really is a good idea...






          share|improve this answer


























          • while this could work whenever we need z, this requires a whole class to be created only for one variable. so i'm preferring the lambda method to be chosen as answer.

            – Michael D. Blake
            Mar 29 at 14:42






          • 5





            @NayWunnaZaw: If it's a one-off usage, sure, use the lambda. But if your code has multiple places where dynamic types like this are needed, a slightly more complex class (templated, receiving a function, e.g. one of the operator wrappers like std::plus) would be only a little longer at time of definition, while supporting reuse without redefining a fairly subtle thing at each point of use. I think this is the better answer for when this is a pattern, not merely a one-off trick.

            – ShadowRanger
            Mar 29 at 16:43











          • @ShadowRanger Yes, I understand that. But it'd be off topic if I accept the class type answer. What I asked is a variable which will get updated whenever x and y are changed. So I think lambda is an appropriate answer for my question.

            – Michael D. Blake
            Mar 29 at 18:21






          • 5





            @NayWunnaZaw: BTW, just to be clear: You realize lambdas are (unnamed) classes, right? They're syntactic sugar around functors (the captures are instance attributes, and the arguments are arguments to operator()) so in both cases a class exists (or doesn't exist due to inlining). This explicitly overrides operator int (so implicit conversion does the trick), where lambdas implicitly override operator() (so explicit call parens are needed), otherwise they're the same. It's fine if you prefer the lambda for code brevity, but in terms of what actually runs, both of them involve classes.

            – ShadowRanger
            Mar 29 at 19:16








          • 1





            @MichaelD.Blake Actually, that's use case dependent. What's fine in one application can turn out to be inefficient in another one...

            – Aconcagua
            Apr 1 at 19:02
















          43














          Edit: While I fully answered the question as asked, please have a look at Artelius' answer, too. It addresses some issues my answer doesn't (encapsulation, avoidance of redundancies, risks of dangling references). A possible optimisation, if calculation is expensive, is shown in Jonathan Mee's answer.





          You mean something like this:



          class Z
          {
          int& x;
          int& y;
          public:
          Z(int& x, int& y) : x(x), y(y) { }
          operator int() { return x + y; }
          };


          The class delays calculation of the result until casted as int. As cast operator is not explicit, Z can be used whenever an int is required. As there's an overload of operator<< for int, you can use it with e. g. std::cout directly:



          int x, y;
          Z z(x, y);
          std::cin >> x >> y;
          if(std::cin) // otherwise, IO error! (e. g. bad user input)
          std::cout << z << std::endl;


          Be aware, though, that there's still a function call (the implicit one of the cast operator), even though it is not visible. And actually the operator does some true calculations (rather than just accessing an internal member), so it is questionable if hiding away the function call really is a good idea...






          share|improve this answer


























          • while this could work whenever we need z, this requires a whole class to be created only for one variable. so i'm preferring the lambda method to be chosen as answer.

            – Michael D. Blake
            Mar 29 at 14:42






          • 5





            @NayWunnaZaw: If it's a one-off usage, sure, use the lambda. But if your code has multiple places where dynamic types like this are needed, a slightly more complex class (templated, receiving a function, e.g. one of the operator wrappers like std::plus) would be only a little longer at time of definition, while supporting reuse without redefining a fairly subtle thing at each point of use. I think this is the better answer for when this is a pattern, not merely a one-off trick.

            – ShadowRanger
            Mar 29 at 16:43











          • @ShadowRanger Yes, I understand that. But it'd be off topic if I accept the class type answer. What I asked is a variable which will get updated whenever x and y are changed. So I think lambda is an appropriate answer for my question.

            – Michael D. Blake
            Mar 29 at 18:21






          • 5





            @NayWunnaZaw: BTW, just to be clear: You realize lambdas are (unnamed) classes, right? They're syntactic sugar around functors (the captures are instance attributes, and the arguments are arguments to operator()) so in both cases a class exists (or doesn't exist due to inlining). This explicitly overrides operator int (so implicit conversion does the trick), where lambdas implicitly override operator() (so explicit call parens are needed), otherwise they're the same. It's fine if you prefer the lambda for code brevity, but in terms of what actually runs, both of them involve classes.

            – ShadowRanger
            Mar 29 at 19:16








          • 1





            @MichaelD.Blake Actually, that's use case dependent. What's fine in one application can turn out to be inefficient in another one...

            – Aconcagua
            Apr 1 at 19:02














          43












          43








          43







          Edit: While I fully answered the question as asked, please have a look at Artelius' answer, too. It addresses some issues my answer doesn't (encapsulation, avoidance of redundancies, risks of dangling references). A possible optimisation, if calculation is expensive, is shown in Jonathan Mee's answer.





          You mean something like this:



          class Z
          {
          int& x;
          int& y;
          public:
          Z(int& x, int& y) : x(x), y(y) { }
          operator int() { return x + y; }
          };


          The class delays calculation of the result until casted as int. As cast operator is not explicit, Z can be used whenever an int is required. As there's an overload of operator<< for int, you can use it with e. g. std::cout directly:



          int x, y;
          Z z(x, y);
          std::cin >> x >> y;
          if(std::cin) // otherwise, IO error! (e. g. bad user input)
          std::cout << z << std::endl;


          Be aware, though, that there's still a function call (the implicit one of the cast operator), even though it is not visible. And actually the operator does some true calculations (rather than just accessing an internal member), so it is questionable if hiding away the function call really is a good idea...






          share|improve this answer















          Edit: While I fully answered the question as asked, please have a look at Artelius' answer, too. It addresses some issues my answer doesn't (encapsulation, avoidance of redundancies, risks of dangling references). A possible optimisation, if calculation is expensive, is shown in Jonathan Mee's answer.





          You mean something like this:



          class Z
          {
          int& x;
          int& y;
          public:
          Z(int& x, int& y) : x(x), y(y) { }
          operator int() { return x + y; }
          };


          The class delays calculation of the result until casted as int. As cast operator is not explicit, Z can be used whenever an int is required. As there's an overload of operator<< for int, you can use it with e. g. std::cout directly:



          int x, y;
          Z z(x, y);
          std::cin >> x >> y;
          if(std::cin) // otherwise, IO error! (e. g. bad user input)
          std::cout << z << std::endl;


          Be aware, though, that there's still a function call (the implicit one of the cast operator), even though it is not visible. And actually the operator does some true calculations (rather than just accessing an internal member), so it is questionable if hiding away the function call really is a good idea...







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 4 at 6:40

























          answered Mar 28 at 16:47









          AconcaguaAconcagua

          13.5k32445




          13.5k32445













          • while this could work whenever we need z, this requires a whole class to be created only for one variable. so i'm preferring the lambda method to be chosen as answer.

            – Michael D. Blake
            Mar 29 at 14:42






          • 5





            @NayWunnaZaw: If it's a one-off usage, sure, use the lambda. But if your code has multiple places where dynamic types like this are needed, a slightly more complex class (templated, receiving a function, e.g. one of the operator wrappers like std::plus) would be only a little longer at time of definition, while supporting reuse without redefining a fairly subtle thing at each point of use. I think this is the better answer for when this is a pattern, not merely a one-off trick.

            – ShadowRanger
            Mar 29 at 16:43











          • @ShadowRanger Yes, I understand that. But it'd be off topic if I accept the class type answer. What I asked is a variable which will get updated whenever x and y are changed. So I think lambda is an appropriate answer for my question.

            – Michael D. Blake
            Mar 29 at 18:21






          • 5





            @NayWunnaZaw: BTW, just to be clear: You realize lambdas are (unnamed) classes, right? They're syntactic sugar around functors (the captures are instance attributes, and the arguments are arguments to operator()) so in both cases a class exists (or doesn't exist due to inlining). This explicitly overrides operator int (so implicit conversion does the trick), where lambdas implicitly override operator() (so explicit call parens are needed), otherwise they're the same. It's fine if you prefer the lambda for code brevity, but in terms of what actually runs, both of them involve classes.

            – ShadowRanger
            Mar 29 at 19:16








          • 1





            @MichaelD.Blake Actually, that's use case dependent. What's fine in one application can turn out to be inefficient in another one...

            – Aconcagua
            Apr 1 at 19:02



















          • while this could work whenever we need z, this requires a whole class to be created only for one variable. so i'm preferring the lambda method to be chosen as answer.

            – Michael D. Blake
            Mar 29 at 14:42






          • 5





            @NayWunnaZaw: If it's a one-off usage, sure, use the lambda. But if your code has multiple places where dynamic types like this are needed, a slightly more complex class (templated, receiving a function, e.g. one of the operator wrappers like std::plus) would be only a little longer at time of definition, while supporting reuse without redefining a fairly subtle thing at each point of use. I think this is the better answer for when this is a pattern, not merely a one-off trick.

            – ShadowRanger
            Mar 29 at 16:43











          • @ShadowRanger Yes, I understand that. But it'd be off topic if I accept the class type answer. What I asked is a variable which will get updated whenever x and y are changed. So I think lambda is an appropriate answer for my question.

            – Michael D. Blake
            Mar 29 at 18:21






          • 5





            @NayWunnaZaw: BTW, just to be clear: You realize lambdas are (unnamed) classes, right? They're syntactic sugar around functors (the captures are instance attributes, and the arguments are arguments to operator()) so in both cases a class exists (or doesn't exist due to inlining). This explicitly overrides operator int (so implicit conversion does the trick), where lambdas implicitly override operator() (so explicit call parens are needed), otherwise they're the same. It's fine if you prefer the lambda for code brevity, but in terms of what actually runs, both of them involve classes.

            – ShadowRanger
            Mar 29 at 19:16








          • 1





            @MichaelD.Blake Actually, that's use case dependent. What's fine in one application can turn out to be inefficient in another one...

            – Aconcagua
            Apr 1 at 19:02

















          while this could work whenever we need z, this requires a whole class to be created only for one variable. so i'm preferring the lambda method to be chosen as answer.

          – Michael D. Blake
          Mar 29 at 14:42





          while this could work whenever we need z, this requires a whole class to be created only for one variable. so i'm preferring the lambda method to be chosen as answer.

          – Michael D. Blake
          Mar 29 at 14:42




          5




          5





          @NayWunnaZaw: If it's a one-off usage, sure, use the lambda. But if your code has multiple places where dynamic types like this are needed, a slightly more complex class (templated, receiving a function, e.g. one of the operator wrappers like std::plus) would be only a little longer at time of definition, while supporting reuse without redefining a fairly subtle thing at each point of use. I think this is the better answer for when this is a pattern, not merely a one-off trick.

          – ShadowRanger
          Mar 29 at 16:43





          @NayWunnaZaw: If it's a one-off usage, sure, use the lambda. But if your code has multiple places where dynamic types like this are needed, a slightly more complex class (templated, receiving a function, e.g. one of the operator wrappers like std::plus) would be only a little longer at time of definition, while supporting reuse without redefining a fairly subtle thing at each point of use. I think this is the better answer for when this is a pattern, not merely a one-off trick.

          – ShadowRanger
          Mar 29 at 16:43













          @ShadowRanger Yes, I understand that. But it'd be off topic if I accept the class type answer. What I asked is a variable which will get updated whenever x and y are changed. So I think lambda is an appropriate answer for my question.

          – Michael D. Blake
          Mar 29 at 18:21





          @ShadowRanger Yes, I understand that. But it'd be off topic if I accept the class type answer. What I asked is a variable which will get updated whenever x and y are changed. So I think lambda is an appropriate answer for my question.

          – Michael D. Blake
          Mar 29 at 18:21




          5




          5





          @NayWunnaZaw: BTW, just to be clear: You realize lambdas are (unnamed) classes, right? They're syntactic sugar around functors (the captures are instance attributes, and the arguments are arguments to operator()) so in both cases a class exists (or doesn't exist due to inlining). This explicitly overrides operator int (so implicit conversion does the trick), where lambdas implicitly override operator() (so explicit call parens are needed), otherwise they're the same. It's fine if you prefer the lambda for code brevity, but in terms of what actually runs, both of them involve classes.

          – ShadowRanger
          Mar 29 at 19:16







          @NayWunnaZaw: BTW, just to be clear: You realize lambdas are (unnamed) classes, right? They're syntactic sugar around functors (the captures are instance attributes, and the arguments are arguments to operator()) so in both cases a class exists (or doesn't exist due to inlining). This explicitly overrides operator int (so implicit conversion does the trick), where lambdas implicitly override operator() (so explicit call parens are needed), otherwise they're the same. It's fine if you prefer the lambda for code brevity, but in terms of what actually runs, both of them involve classes.

          – ShadowRanger
          Mar 29 at 19:16






          1




          1





          @MichaelD.Blake Actually, that's use case dependent. What's fine in one application can turn out to be inefficient in another one...

          – Aconcagua
          Apr 1 at 19:02





          @MichaelD.Blake Actually, that's use case dependent. What's fine in one application can turn out to be inefficient in another one...

          – Aconcagua
          Apr 1 at 19:02













          43














          You can get close to this with by using a lambda in C++. Generally, when you set a variable like



          int x;
          int y;
          int z{x + y};


          z will only be the result of x + y at that time. You'd have to do z = x + y; every time you change x or y to keep it update.



          If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like



          int x;
          int y;
          auto z = [&](){ return x + y; };
          cin >> x;
          cin >> y;
          cout << z();


          and now z() will have the correct value instead of the uninitialized garbage that the original code had.



          If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like



          auto z = [&](){ static auto cache_x = x; 
          static auto cache_y = y;
          static auto cache_result = x + y;
          if (x != cache_x || y != cache_y)
          {
          cache_x = x;
          cache_y = y;
          cache_result = x + y;
          }
          return cache_result;
          };





          share|improve this answer





















          • 2





            Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

            – Max Langhof
            Mar 28 at 17:03






          • 7





            And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

            – Mooing Duck
            Mar 28 at 22:25











          • @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

            – Fabio Turati
            Mar 28 at 23:34











          • @FabioTurati See Aconcagua's answer

            – NathanOliver
            Mar 28 at 23:48






          • 7





            Erm you probably don't want static for caching... lambdas can be stateful for a reason.

            – Mehrdad
            Mar 29 at 6:47


















          43














          You can get close to this with by using a lambda in C++. Generally, when you set a variable like



          int x;
          int y;
          int z{x + y};


          z will only be the result of x + y at that time. You'd have to do z = x + y; every time you change x or y to keep it update.



          If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like



          int x;
          int y;
          auto z = [&](){ return x + y; };
          cin >> x;
          cin >> y;
          cout << z();


          and now z() will have the correct value instead of the uninitialized garbage that the original code had.



          If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like



          auto z = [&](){ static auto cache_x = x; 
          static auto cache_y = y;
          static auto cache_result = x + y;
          if (x != cache_x || y != cache_y)
          {
          cache_x = x;
          cache_y = y;
          cache_result = x + y;
          }
          return cache_result;
          };





          share|improve this answer





















          • 2





            Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

            – Max Langhof
            Mar 28 at 17:03






          • 7





            And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

            – Mooing Duck
            Mar 28 at 22:25











          • @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

            – Fabio Turati
            Mar 28 at 23:34











          • @FabioTurati See Aconcagua's answer

            – NathanOliver
            Mar 28 at 23:48






          • 7





            Erm you probably don't want static for caching... lambdas can be stateful for a reason.

            – Mehrdad
            Mar 29 at 6:47
















          43












          43








          43







          You can get close to this with by using a lambda in C++. Generally, when you set a variable like



          int x;
          int y;
          int z{x + y};


          z will only be the result of x + y at that time. You'd have to do z = x + y; every time you change x or y to keep it update.



          If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like



          int x;
          int y;
          auto z = [&](){ return x + y; };
          cin >> x;
          cin >> y;
          cout << z();


          and now z() will have the correct value instead of the uninitialized garbage that the original code had.



          If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like



          auto z = [&](){ static auto cache_x = x; 
          static auto cache_y = y;
          static auto cache_result = x + y;
          if (x != cache_x || y != cache_y)
          {
          cache_x = x;
          cache_y = y;
          cache_result = x + y;
          }
          return cache_result;
          };





          share|improve this answer















          You can get close to this with by using a lambda in C++. Generally, when you set a variable like



          int x;
          int y;
          int z{x + y};


          z will only be the result of x + y at that time. You'd have to do z = x + y; every time you change x or y to keep it update.



          If you use a lambda though, you can have it capture what objects it should refer to, and what calculation should be done, and then every time you access the lambda it will give you the result at that point in time. That looks like



          int x;
          int y;
          auto z = [&](){ return x + y; };
          cin >> x;
          cin >> y;
          cout << z();


          and now z() will have the correct value instead of the uninitialized garbage that the original code had.



          If the computation is very expensive you can even add some caching to the lambda to make sure you aren't running the computation when you don't need to. That would look like



          auto z = [&](){ static auto cache_x = x; 
          static auto cache_y = y;
          static auto cache_result = x + y;
          if (x != cache_x || y != cache_y)
          {
          cache_x = x;
          cache_y = y;
          cache_result = x + y;
          }
          return cache_result;
          };






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 29 at 16:29









          J.G.

          1259




          1259










          answered Mar 28 at 16:47









          NathanOliverNathanOliver

          98.5k16138218




          98.5k16138218








          • 2





            Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

            – Max Langhof
            Mar 28 at 17:03






          • 7





            And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

            – Mooing Duck
            Mar 28 at 22:25











          • @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

            – Fabio Turati
            Mar 28 at 23:34











          • @FabioTurati See Aconcagua's answer

            – NathanOliver
            Mar 28 at 23:48






          • 7





            Erm you probably don't want static for caching... lambdas can be stateful for a reason.

            – Mehrdad
            Mar 29 at 6:47
















          • 2





            Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

            – Max Langhof
            Mar 28 at 17:03






          • 7





            And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

            – Mooing Duck
            Mar 28 at 22:25











          • @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

            – Fabio Turati
            Mar 28 at 23:34











          • @FabioTurati See Aconcagua's answer

            – NathanOliver
            Mar 28 at 23:48






          • 7





            Erm you probably don't want static for caching... lambdas can be stateful for a reason.

            – Mehrdad
            Mar 29 at 6:47










          2




          2





          Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

          – Max Langhof
          Mar 28 at 17:03





          Also, at that point you should not repeat the cache code for each kind of lambda. A class encapsulation is pretty much required there.

          – Max Langhof
          Mar 28 at 17:03




          7




          7





          And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

          – Mooing Duck
          Mar 28 at 22:25





          And a class can be used to avoid the z() syntax as well: coliru.stacked-crooked.com/a/3c3dafe9856c28b8

          – Mooing Duck
          Mar 28 at 22:25













          @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

          – Fabio Turati
          Mar 28 at 23:34





          @MooingDuck That's awesome! I didn't think it was possible. It deserves to be an answer on its own!

          – Fabio Turati
          Mar 28 at 23:34













          @FabioTurati See Aconcagua's answer

          – NathanOliver
          Mar 28 at 23:48





          @FabioTurati See Aconcagua's answer

          – NathanOliver
          Mar 28 at 23:48




          7




          7





          Erm you probably don't want static for caching... lambdas can be stateful for a reason.

          – Mehrdad
          Mar 29 at 6:47







          Erm you probably don't want static for caching... lambdas can be stateful for a reason.

          – Mehrdad
          Mar 29 at 6:47













          21














          The closest you probably can get is to create a functor:



          #include <iostream>

          int main() {
          int x;
          int y;

          auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y

          while(true) {
          std::cin >> x;
          std::cin >> y;
          std::cout << z() << "n";
          }
          }





          share|improve this answer




























            21














            The closest you probably can get is to create a functor:



            #include <iostream>

            int main() {
            int x;
            int y;

            auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y

            while(true) {
            std::cin >> x;
            std::cin >> y;
            std::cout << z() << "n";
            }
            }





            share|improve this answer


























              21












              21








              21







              The closest you probably can get is to create a functor:



              #include <iostream>

              int main() {
              int x;
              int y;

              auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y

              while(true) {
              std::cin >> x;
              std::cin >> y;
              std::cout << z() << "n";
              }
              }





              share|improve this answer













              The closest you probably can get is to create a functor:



              #include <iostream>

              int main() {
              int x;
              int y;

              auto z = [&x, &y] { return x + y; }; // a lambda capturing x and y

              while(true) {
              std::cin >> x;
              std::cin >> y;
              std::cout << z() << "n";
              }
              }






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Mar 28 at 16:48









              Ted LyngmoTed Lyngmo

              3,8382522




              3,8382522























                  18














                  There are two chief techniques:




                  1. Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type (as in Aconcagua's answer).


                  2. Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).



                  The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.






                  share|improve this answer





















                  • 1





                    The observation approach is interesting, too, if calculations to be done are expensive. Appropriately implemented, I consider it more elegant than the caching proposed by NathanOliver...

                    – Aconcagua
                    Mar 29 at 9:27






                  • 4





                    @Aconcagua, amend that to: if calculations to be done are expensive and reads are more frequent than updates. Otherwise, we need to add a way to avoid computing values that don't get used.

                    – Toby Speight
                    Mar 29 at 12:18
















                  18














                  There are two chief techniques:




                  1. Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type (as in Aconcagua's answer).


                  2. Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).



                  The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.






                  share|improve this answer





















                  • 1





                    The observation approach is interesting, too, if calculations to be done are expensive. Appropriately implemented, I consider it more elegant than the caching proposed by NathanOliver...

                    – Aconcagua
                    Mar 29 at 9:27






                  • 4





                    @Aconcagua, amend that to: if calculations to be done are expensive and reads are more frequent than updates. Otherwise, we need to add a way to avoid computing values that don't get used.

                    – Toby Speight
                    Mar 29 at 12:18














                  18












                  18








                  18







                  There are two chief techniques:




                  1. Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type (as in Aconcagua's answer).


                  2. Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).



                  The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.






                  share|improve this answer















                  There are two chief techniques:




                  1. Deferred calculation - instead of z being a simple variable, make it a function which calculates the value on demand (see other answers for examples). This can be source-code transparent if z is some proxy object with implicit conversion to the required type (as in Aconcagua's answer).


                  2. Explicit notification of changes. This requires x and y to be observable types; when either changes value, then z updates itself (and notifies its observers if applicable).



                  The first version is usually preferred, but the second may be more appropriate if you need z to be an observable type.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 29 at 12:20

























                  answered Mar 28 at 20:02









                  Toby SpeightToby Speight

                  17.5k134469




                  17.5k134469








                  • 1





                    The observation approach is interesting, too, if calculations to be done are expensive. Appropriately implemented, I consider it more elegant than the caching proposed by NathanOliver...

                    – Aconcagua
                    Mar 29 at 9:27






                  • 4





                    @Aconcagua, amend that to: if calculations to be done are expensive and reads are more frequent than updates. Otherwise, we need to add a way to avoid computing values that don't get used.

                    – Toby Speight
                    Mar 29 at 12:18














                  • 1





                    The observation approach is interesting, too, if calculations to be done are expensive. Appropriately implemented, I consider it more elegant than the caching proposed by NathanOliver...

                    – Aconcagua
                    Mar 29 at 9:27






                  • 4





                    @Aconcagua, amend that to: if calculations to be done are expensive and reads are more frequent than updates. Otherwise, we need to add a way to avoid computing values that don't get used.

                    – Toby Speight
                    Mar 29 at 12:18








                  1




                  1





                  The observation approach is interesting, too, if calculations to be done are expensive. Appropriately implemented, I consider it more elegant than the caching proposed by NathanOliver...

                  – Aconcagua
                  Mar 29 at 9:27





                  The observation approach is interesting, too, if calculations to be done are expensive. Appropriately implemented, I consider it more elegant than the caching proposed by NathanOliver...

                  – Aconcagua
                  Mar 29 at 9:27




                  4




                  4





                  @Aconcagua, amend that to: if calculations to be done are expensive and reads are more frequent than updates. Otherwise, we need to add a way to avoid computing values that don't get used.

                  – Toby Speight
                  Mar 29 at 12:18





                  @Aconcagua, amend that to: if calculations to be done are expensive and reads are more frequent than updates. Otherwise, we need to add a way to avoid computing values that don't get used.

                  – Toby Speight
                  Mar 29 at 12:18











                  14














                  This sounds like the XY problem (pun intended).



                  From the sound of it, you are not really writing code according to good object oriented practices. I would advise you not to use the "tricks" other people have suggested, but to actually learn how to make better use of OO structure.



                  Before I go into that, note that assignment is distinct from an equality relation. The = in C++ is assignment, which is not the same as the = in maths. There are some (but not many) programming languages that do support equality relations, but C++ is not one of them. The thing is, adding support for equality relations introduces a heap of new challenges, so it's not as simple as "why isn't it in C++ yet".



                  Anyway, in this case, you should probably be encapsulating your related variables in a class. Then you can use methods to obtain the "up-to-date" information. For example:



                  class Player {
                  std::vector<int> inventory;
                  int cash;
                  public:
                  int inventory_total();
                  int net_worth();
                  }

                  //adds up total value of inventory
                  int Player::inventory_total() {
                  int total = 0;
                  for(std::vector<int>::iterator it = inventory.begin(); it != inventory.end(); ++it) {
                  total += *it;
                  }
                  return total;
                  }

                  //calculates net worth
                  int Player::net_worth() {
                  //we are using inventory_total() as if it were a variable that automatically
                  //holds the sum of the inventory values
                  return inventory_total() + cash;
                  }


                  ...


                  //we are using net_worth() as if it were a variable that automatically
                  //holds the sum of the cash and total holdings
                  std::cout << player1.net_worth();


                  I admit that adding this behaviour to a class is quite a bit more complicated than saying z = x + y, but it really is only a few extra lines of code.




                  That would be very annoying and error prone if you forgot to call the function somewhere.




                  In this case the object doesn't have a net_worth member variable, so you can't accidentally use it instead of calling the function.






                  share|improve this answer


























                  • can you give me the pros and cons of using lambdas vs this? which would be better practice?

                    – Michael D. Blake
                    Mar 29 at 13:33






                  • 1





                    Yes, this is the (real) answer I would expect. Unfortunately, there is FGITW (I think it is a real problem).

                    – Peter Mortensen
                    Mar 30 at 1:44











                  • Maybe worth to mention: Such a separate net_worth variable would introduce redundancy. There's a parallel to DBMS: You try to avoid any kind of redundancies there, too – at first place, at least, later, they can get re-introduced to speed up specific frequently used requests – which leads back to answer: iterating over the vector all the time might turn out to be too costly, so we might end up in caching the sum in a variable (again). But that shouldn't enter the design right at the start, it's an optimisation that only should get introduced on need (after analysis/profiling).

                    – Aconcagua
                    Apr 4 at 6:19
















                  14














                  This sounds like the XY problem (pun intended).



                  From the sound of it, you are not really writing code according to good object oriented practices. I would advise you not to use the "tricks" other people have suggested, but to actually learn how to make better use of OO structure.



                  Before I go into that, note that assignment is distinct from an equality relation. The = in C++ is assignment, which is not the same as the = in maths. There are some (but not many) programming languages that do support equality relations, but C++ is not one of them. The thing is, adding support for equality relations introduces a heap of new challenges, so it's not as simple as "why isn't it in C++ yet".



                  Anyway, in this case, you should probably be encapsulating your related variables in a class. Then you can use methods to obtain the "up-to-date" information. For example:



                  class Player {
                  std::vector<int> inventory;
                  int cash;
                  public:
                  int inventory_total();
                  int net_worth();
                  }

                  //adds up total value of inventory
                  int Player::inventory_total() {
                  int total = 0;
                  for(std::vector<int>::iterator it = inventory.begin(); it != inventory.end(); ++it) {
                  total += *it;
                  }
                  return total;
                  }

                  //calculates net worth
                  int Player::net_worth() {
                  //we are using inventory_total() as if it were a variable that automatically
                  //holds the sum of the inventory values
                  return inventory_total() + cash;
                  }


                  ...


                  //we are using net_worth() as if it were a variable that automatically
                  //holds the sum of the cash and total holdings
                  std::cout << player1.net_worth();


                  I admit that adding this behaviour to a class is quite a bit more complicated than saying z = x + y, but it really is only a few extra lines of code.




                  That would be very annoying and error prone if you forgot to call the function somewhere.




                  In this case the object doesn't have a net_worth member variable, so you can't accidentally use it instead of calling the function.






                  share|improve this answer


























                  • can you give me the pros and cons of using lambdas vs this? which would be better practice?

                    – Michael D. Blake
                    Mar 29 at 13:33






                  • 1





                    Yes, this is the (real) answer I would expect. Unfortunately, there is FGITW (I think it is a real problem).

                    – Peter Mortensen
                    Mar 30 at 1:44











                  • Maybe worth to mention: Such a separate net_worth variable would introduce redundancy. There's a parallel to DBMS: You try to avoid any kind of redundancies there, too – at first place, at least, later, they can get re-introduced to speed up specific frequently used requests – which leads back to answer: iterating over the vector all the time might turn out to be too costly, so we might end up in caching the sum in a variable (again). But that shouldn't enter the design right at the start, it's an optimisation that only should get introduced on need (after analysis/profiling).

                    – Aconcagua
                    Apr 4 at 6:19














                  14












                  14








                  14







                  This sounds like the XY problem (pun intended).



                  From the sound of it, you are not really writing code according to good object oriented practices. I would advise you not to use the "tricks" other people have suggested, but to actually learn how to make better use of OO structure.



                  Before I go into that, note that assignment is distinct from an equality relation. The = in C++ is assignment, which is not the same as the = in maths. There are some (but not many) programming languages that do support equality relations, but C++ is not one of them. The thing is, adding support for equality relations introduces a heap of new challenges, so it's not as simple as "why isn't it in C++ yet".



                  Anyway, in this case, you should probably be encapsulating your related variables in a class. Then you can use methods to obtain the "up-to-date" information. For example:



                  class Player {
                  std::vector<int> inventory;
                  int cash;
                  public:
                  int inventory_total();
                  int net_worth();
                  }

                  //adds up total value of inventory
                  int Player::inventory_total() {
                  int total = 0;
                  for(std::vector<int>::iterator it = inventory.begin(); it != inventory.end(); ++it) {
                  total += *it;
                  }
                  return total;
                  }

                  //calculates net worth
                  int Player::net_worth() {
                  //we are using inventory_total() as if it were a variable that automatically
                  //holds the sum of the inventory values
                  return inventory_total() + cash;
                  }


                  ...


                  //we are using net_worth() as if it were a variable that automatically
                  //holds the sum of the cash and total holdings
                  std::cout << player1.net_worth();


                  I admit that adding this behaviour to a class is quite a bit more complicated than saying z = x + y, but it really is only a few extra lines of code.




                  That would be very annoying and error prone if you forgot to call the function somewhere.




                  In this case the object doesn't have a net_worth member variable, so you can't accidentally use it instead of calling the function.






                  share|improve this answer















                  This sounds like the XY problem (pun intended).



                  From the sound of it, you are not really writing code according to good object oriented practices. I would advise you not to use the "tricks" other people have suggested, but to actually learn how to make better use of OO structure.



                  Before I go into that, note that assignment is distinct from an equality relation. The = in C++ is assignment, which is not the same as the = in maths. There are some (but not many) programming languages that do support equality relations, but C++ is not one of them. The thing is, adding support for equality relations introduces a heap of new challenges, so it's not as simple as "why isn't it in C++ yet".



                  Anyway, in this case, you should probably be encapsulating your related variables in a class. Then you can use methods to obtain the "up-to-date" information. For example:



                  class Player {
                  std::vector<int> inventory;
                  int cash;
                  public:
                  int inventory_total();
                  int net_worth();
                  }

                  //adds up total value of inventory
                  int Player::inventory_total() {
                  int total = 0;
                  for(std::vector<int>::iterator it = inventory.begin(); it != inventory.end(); ++it) {
                  total += *it;
                  }
                  return total;
                  }

                  //calculates net worth
                  int Player::net_worth() {
                  //we are using inventory_total() as if it were a variable that automatically
                  //holds the sum of the inventory values
                  return inventory_total() + cash;
                  }


                  ...


                  //we are using net_worth() as if it were a variable that automatically
                  //holds the sum of the cash and total holdings
                  std::cout << player1.net_worth();


                  I admit that adding this behaviour to a class is quite a bit more complicated than saying z = x + y, but it really is only a few extra lines of code.




                  That would be very annoying and error prone if you forgot to call the function somewhere.




                  In this case the object doesn't have a net_worth member variable, so you can't accidentally use it instead of calling the function.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 29 at 16:49









                  ShadowRanger

                  63.9k660100




                  63.9k660100










                  answered Mar 29 at 6:59









                  ArteliusArtelius

                  41.6k87896




                  41.6k87896













                  • can you give me the pros and cons of using lambdas vs this? which would be better practice?

                    – Michael D. Blake
                    Mar 29 at 13:33






                  • 1





                    Yes, this is the (real) answer I would expect. Unfortunately, there is FGITW (I think it is a real problem).

                    – Peter Mortensen
                    Mar 30 at 1:44











                  • Maybe worth to mention: Such a separate net_worth variable would introduce redundancy. There's a parallel to DBMS: You try to avoid any kind of redundancies there, too – at first place, at least, later, they can get re-introduced to speed up specific frequently used requests – which leads back to answer: iterating over the vector all the time might turn out to be too costly, so we might end up in caching the sum in a variable (again). But that shouldn't enter the design right at the start, it's an optimisation that only should get introduced on need (after analysis/profiling).

                    – Aconcagua
                    Apr 4 at 6:19



















                  • can you give me the pros and cons of using lambdas vs this? which would be better practice?

                    – Michael D. Blake
                    Mar 29 at 13:33






                  • 1





                    Yes, this is the (real) answer I would expect. Unfortunately, there is FGITW (I think it is a real problem).

                    – Peter Mortensen
                    Mar 30 at 1:44











                  • Maybe worth to mention: Such a separate net_worth variable would introduce redundancy. There's a parallel to DBMS: You try to avoid any kind of redundancies there, too – at first place, at least, later, they can get re-introduced to speed up specific frequently used requests – which leads back to answer: iterating over the vector all the time might turn out to be too costly, so we might end up in caching the sum in a variable (again). But that shouldn't enter the design right at the start, it's an optimisation that only should get introduced on need (after analysis/profiling).

                    – Aconcagua
                    Apr 4 at 6:19

















                  can you give me the pros and cons of using lambdas vs this? which would be better practice?

                  – Michael D. Blake
                  Mar 29 at 13:33





                  can you give me the pros and cons of using lambdas vs this? which would be better practice?

                  – Michael D. Blake
                  Mar 29 at 13:33




                  1




                  1





                  Yes, this is the (real) answer I would expect. Unfortunately, there is FGITW (I think it is a real problem).

                  – Peter Mortensen
                  Mar 30 at 1:44





                  Yes, this is the (real) answer I would expect. Unfortunately, there is FGITW (I think it is a real problem).

                  – Peter Mortensen
                  Mar 30 at 1:44













                  Maybe worth to mention: Such a separate net_worth variable would introduce redundancy. There's a parallel to DBMS: You try to avoid any kind of redundancies there, too – at first place, at least, later, they can get re-introduced to speed up specific frequently used requests – which leads back to answer: iterating over the vector all the time might turn out to be too costly, so we might end up in caching the sum in a variable (again). But that shouldn't enter the design right at the start, it's an optimisation that only should get introduced on need (after analysis/profiling).

                  – Aconcagua
                  Apr 4 at 6:19





                  Maybe worth to mention: Such a separate net_worth variable would introduce redundancy. There's a parallel to DBMS: You try to avoid any kind of redundancies there, too – at first place, at least, later, they can get re-introduced to speed up specific frequently used requests – which leads back to answer: iterating over the vector all the time might turn out to be too costly, so we might end up in caching the sum in a variable (again). But that shouldn't enter the design right at the start, it's an optimisation that only should get introduced on need (after analysis/profiling).

                  – Aconcagua
                  Apr 4 at 6:19











                  7















                  1. You create a function for that.

                  2. You call the function with the appropriate arguments when you need the value.




                  int z(int x, int y)
                  {
                  return (x + y);
                  }


                  int x;
                  int y;

                  // This does ot work
                  // int z{x + y};

                  cin >> x;
                  cin >> y;
                  cout << z(x, y);





                  share|improve this answer



















                  • 1





                    yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                    – Michael D. Blake
                    Mar 28 at 16:54











                  • @NayWunnaZaw, yes, that is correct.

                    – R Sahu
                    Mar 28 at 16:55






                  • 1





                    @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                    – R Sahu
                    Mar 28 at 16:57






                  • 4





                    @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                    – Aconcagua
                    Mar 28 at 17:04
















                  7















                  1. You create a function for that.

                  2. You call the function with the appropriate arguments when you need the value.




                  int z(int x, int y)
                  {
                  return (x + y);
                  }


                  int x;
                  int y;

                  // This does ot work
                  // int z{x + y};

                  cin >> x;
                  cin >> y;
                  cout << z(x, y);





                  share|improve this answer



















                  • 1





                    yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                    – Michael D. Blake
                    Mar 28 at 16:54











                  • @NayWunnaZaw, yes, that is correct.

                    – R Sahu
                    Mar 28 at 16:55






                  • 1





                    @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                    – R Sahu
                    Mar 28 at 16:57






                  • 4





                    @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                    – Aconcagua
                    Mar 28 at 17:04














                  7












                  7








                  7








                  1. You create a function for that.

                  2. You call the function with the appropriate arguments when you need the value.




                  int z(int x, int y)
                  {
                  return (x + y);
                  }


                  int x;
                  int y;

                  // This does ot work
                  // int z{x + y};

                  cin >> x;
                  cin >> y;
                  cout << z(x, y);





                  share|improve this answer














                  1. You create a function for that.

                  2. You call the function with the appropriate arguments when you need the value.




                  int z(int x, int y)
                  {
                  return (x + y);
                  }


                  int x;
                  int y;

                  // This does ot work
                  // int z{x + y};

                  cin >> x;
                  cin >> y;
                  cout << z(x, y);






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 28 at 16:47









                  R SahuR Sahu

                  171k1297195




                  171k1297195








                  • 1





                    yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                    – Michael D. Blake
                    Mar 28 at 16:54











                  • @NayWunnaZaw, yes, that is correct.

                    – R Sahu
                    Mar 28 at 16:55






                  • 1





                    @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                    – R Sahu
                    Mar 28 at 16:57






                  • 4





                    @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                    – Aconcagua
                    Mar 28 at 17:04














                  • 1





                    yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                    – Michael D. Blake
                    Mar 28 at 16:54











                  • @NayWunnaZaw, yes, that is correct.

                    – R Sahu
                    Mar 28 at 16:55






                  • 1





                    @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                    – R Sahu
                    Mar 28 at 16:57






                  • 4





                    @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                    – Aconcagua
                    Mar 28 at 17:04








                  1




                  1





                  yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                  – Michael D. Blake
                  Mar 28 at 16:54





                  yes, i mean the only way to get z updated is to call that function everytime we change x and y values?

                  – Michael D. Blake
                  Mar 28 at 16:54













                  @NayWunnaZaw, yes, that is correct.

                  – R Sahu
                  Mar 28 at 16:55





                  @NayWunnaZaw, yes, that is correct.

                  – R Sahu
                  Mar 28 at 16:55




                  1




                  1





                  @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                  – R Sahu
                  Mar 28 at 16:57





                  @NayWunnaZaw, you can avoid the repeated use of x and y by using a lambda function, as shown by Nathan but you still have to make the call.

                  – R Sahu
                  Mar 28 at 16:57




                  4




                  4





                  @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                  – Aconcagua
                  Mar 28 at 17:04





                  @NayWunnaZaw To complete the issue: Even with my solution, there is a function call (to the cast operator!), just that it is implicit and not required explicitly...

                  – Aconcagua
                  Mar 28 at 17:04











                  4














                  You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:



                  DEMO



                  int main()
                  {
                  int x;
                  int y;

                  const auto z = [&x, &y](){ return x+y; };

                  std::cin >> x; // 1
                  std::cin >> y; // 2
                  std::cout << z() << std::endl; // 3

                  std::cin >> x; // 3
                  std::cin >> y; // 4
                  std::cout << z() << std::endl; // 7
                  }





                  share|improve this answer





















                  • 2





                    Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                    – Aconcagua
                    Mar 28 at 16:53











                  • @Aconcagua thx! you are right. I edited my answer.

                    – Hiroki
                    Mar 28 at 16:54













                  • Why downvoted ? At least I posted my answer faster than Ted with my tested code. Hmm... :)

                    – Hiroki
                    Mar 29 at 9:30








                  • 1





                    Well, I didn't and wouldn't have considered the parentheses worth doing so either. If they were the reason – well, people tend to never come back to remove a DV even if the answer was fixed, so (I don't think there's a notification for either, so people might just not even recognise...)

                    – Aconcagua
                    Mar 29 at 9:44











                  • @Aconcagua thx for your comment. Although I was downvoted after few hours later of my edition, I was relieved to hear your words.

                    – Hiroki
                    Mar 29 at 20:36
















                  4














                  You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:



                  DEMO



                  int main()
                  {
                  int x;
                  int y;

                  const auto z = [&x, &y](){ return x+y; };

                  std::cin >> x; // 1
                  std::cin >> y; // 2
                  std::cout << z() << std::endl; // 3

                  std::cin >> x; // 3
                  std::cin >> y; // 4
                  std::cout << z() << std::endl; // 7
                  }





                  share|improve this answer





















                  • 2





                    Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                    – Aconcagua
                    Mar 28 at 16:53











                  • @Aconcagua thx! you are right. I edited my answer.

                    – Hiroki
                    Mar 28 at 16:54













                  • Why downvoted ? At least I posted my answer faster than Ted with my tested code. Hmm... :)

                    – Hiroki
                    Mar 29 at 9:30








                  • 1





                    Well, I didn't and wouldn't have considered the parentheses worth doing so either. If they were the reason – well, people tend to never come back to remove a DV even if the answer was fixed, so (I don't think there's a notification for either, so people might just not even recognise...)

                    – Aconcagua
                    Mar 29 at 9:44











                  • @Aconcagua thx for your comment. Although I was downvoted after few hours later of my edition, I was relieved to hear your words.

                    – Hiroki
                    Mar 29 at 20:36














                  4












                  4








                  4







                  You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:



                  DEMO



                  int main()
                  {
                  int x;
                  int y;

                  const auto z = [&x, &y](){ return x+y; };

                  std::cin >> x; // 1
                  std::cin >> y; // 2
                  std::cout << z() << std::endl; // 3

                  std::cin >> x; // 3
                  std::cin >> y; // 4
                  std::cout << z() << std::endl; // 7
                  }





                  share|improve this answer















                  You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:



                  DEMO



                  int main()
                  {
                  int x;
                  int y;

                  const auto z = [&x, &y](){ return x+y; };

                  std::cin >> x; // 1
                  std::cin >> y; // 2
                  std::cout << z() << std::endl; // 3

                  std::cin >> x; // 3
                  std::cin >> y; // 4
                  std::cout << z() << std::endl; // 7
                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 29 at 9:29

























                  answered Mar 28 at 16:47









                  HirokiHiroki

                  2,2753522




                  2,2753522








                  • 2





                    Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                    – Aconcagua
                    Mar 28 at 16:53











                  • @Aconcagua thx! you are right. I edited my answer.

                    – Hiroki
                    Mar 28 at 16:54













                  • Why downvoted ? At least I posted my answer faster than Ted with my tested code. Hmm... :)

                    – Hiroki
                    Mar 29 at 9:30








                  • 1





                    Well, I didn't and wouldn't have considered the parentheses worth doing so either. If they were the reason – well, people tend to never come back to remove a DV even if the answer was fixed, so (I don't think there's a notification for either, so people might just not even recognise...)

                    – Aconcagua
                    Mar 29 at 9:44











                  • @Aconcagua thx for your comment. Although I was downvoted after few hours later of my edition, I was relieved to hear your words.

                    – Hiroki
                    Mar 29 at 20:36














                  • 2





                    Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                    – Aconcagua
                    Mar 28 at 16:53











                  • @Aconcagua thx! you are right. I edited my answer.

                    – Hiroki
                    Mar 28 at 16:54













                  • Why downvoted ? At least I posted my answer faster than Ted with my tested code. Hmm... :)

                    – Hiroki
                    Mar 29 at 9:30








                  • 1





                    Well, I didn't and wouldn't have considered the parentheses worth doing so either. If they were the reason – well, people tend to never come back to remove a DV even if the answer was fixed, so (I don't think there's a notification for either, so people might just not even recognise...)

                    – Aconcagua
                    Mar 29 at 9:44











                  • @Aconcagua thx for your comment. Although I was downvoted after few hours later of my edition, I was relieved to hear your words.

                    – Hiroki
                    Mar 29 at 20:36








                  2




                  2





                  Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                  – Aconcagua
                  Mar 28 at 16:53





                  Don't use parentheses around return values – return is not a function, and in worst case, the parentheses can even create a dangling reference (with return type being decltype(auto)).

                  – Aconcagua
                  Mar 28 at 16:53













                  @Aconcagua thx! you are right. I edited my answer.

                  – Hiroki
                  Mar 28 at 16:54







                  @Aconcagua thx! you are right. I edited my answer.

                  – Hiroki
                  Mar 28 at 16:54















                  Why downvoted ? At least I posted my answer faster than Ted with my tested code. Hmm... :)

                  – Hiroki
                  Mar 29 at 9:30







                  Why downvoted ? At least I posted my answer faster than Ted with my tested code. Hmm... :)

                  – Hiroki
                  Mar 29 at 9:30






                  1




                  1





                  Well, I didn't and wouldn't have considered the parentheses worth doing so either. If they were the reason – well, people tend to never come back to remove a DV even if the answer was fixed, so (I don't think there's a notification for either, so people might just not even recognise...)

                  – Aconcagua
                  Mar 29 at 9:44





                  Well, I didn't and wouldn't have considered the parentheses worth doing so either. If they were the reason – well, people tend to never come back to remove a DV even if the answer was fixed, so (I don't think there's a notification for either, so people might just not even recognise...)

                  – Aconcagua
                  Mar 29 at 9:44













                  @Aconcagua thx for your comment. Although I was downvoted after few hours later of my edition, I was relieved to hear your words.

                  – Hiroki
                  Mar 29 at 20:36





                  @Aconcagua thx for your comment. Although I was downvoted after few hours later of my edition, I was relieved to hear your words.

                  – Hiroki
                  Mar 29 at 20:36











                  4














                  So a big problem that I see with the lambda solutions provided is that z is calculated each time that it is inspected even if neither x nor y has changed. To get around this you really need to link these variables.
                  I would suggest doing that via class:



                  class foo {
                  int x;
                  int y;
                  int z;
                  void calculate() { z = (x + y) / 2; }
                  friend istream& operator >>(istream& lhs, foo& rhs);
                  public:
                  void set_x(const int param) {
                  x = param;
                  calculate();
                  }
                  int get_x() const { return x; }
                  void set_y(const int param) {
                  y = param;
                  calculate();
                  }
                  int get_y() const { return y; }
                  int get_z() const { return z; }
                  };

                  istream& operator >>(istream& lhs, foo& rhs) {
                  lhs >> rhs.x >> rhs.y;
                  rhs.calculate();
                  return lhs;
                  }


                  This will recalculate z each time x or y is set. This is a good solution if you access z frequently, and x and y are set infrequently. If x and y are set frequently or calculate is expensive you might consider:



                  class foo {
                  int x;
                  int y;
                  int z;
                  bool dirty;
                  void calculate() { z = (x + y) / 2; }
                  friend istream& operator >>(istream& lhs, foo& rhs);
                  public:
                  void set_x(const int param) {
                  x = param;
                  dirty = true;
                  }
                  int get_x() const { return x; }
                  void set_y(const int param) {
                  y = param;
                  dirty = true;
                  }
                  int get_y() const { return y; }
                  int get_z() const {
                  if(dirty) {
                  calculate();
                  }
                  return z;
                  }
                  };

                  istream& operator >>(istream& lhs, foo& rhs) {
                  lhs >> rhs.x >> rhs.y;
                  rhs.dirty = true;
                  return lhs;
                  }


                  Note that I've included an extraction operator, so whichever you choose your code can turn into something as simple as:



                  foo xyz;

                  cin >> xyz;
                  cout << xyz.get_z();





                  share|improve this answer
























                  • I don't quite understand how lambda work. But if you've played dota you'd know how gold in the game work. The way it is displayed all the time and adding 1 gold every split-second. I'm asking this question with that in mind. How do I implement that in c++?

                    – Michael D. Blake
                    Mar 29 at 18:47






                  • 2





                    @NayWunnaZaw I mean generally you're going to have a main class which calls the tick function on any class that needs live updating, passing in a time elapsed since last tick parameter. You'd probably have a player class instead of just the simple foo which would do loads of things. Like the player class's tick would need to update the damage of poison effects, calculate cooldown times, and also calculate gold. I recognize this is probably a gross over simplification. But I do think you're going to want to go with a class here.

                    – Jonathan Mee
                    Mar 29 at 18:58











                  • thanks for that, but I like lambda answer more for it's simplicity for a variable. and that fits my question. And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there.

                    – Michael D. Blake
                    Mar 29 at 19:10











                  • @MichaelD.Blake There are always lots of solutions to a problem; as the actual programmer you are always in the best place to make that decision. But I do have some concerns as the statement: "And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there." That's the point of the class... it only calculates when required. The lambda will calculate every time you call it... Which is potentially very wasteful... But both the class and the lambda are wasteful if you're only finding z once. Is that where you're at?

                    – Jonathan Mee
                    Apr 4 at 12:38
















                  4














                  So a big problem that I see with the lambda solutions provided is that z is calculated each time that it is inspected even if neither x nor y has changed. To get around this you really need to link these variables.
                  I would suggest doing that via class:



                  class foo {
                  int x;
                  int y;
                  int z;
                  void calculate() { z = (x + y) / 2; }
                  friend istream& operator >>(istream& lhs, foo& rhs);
                  public:
                  void set_x(const int param) {
                  x = param;
                  calculate();
                  }
                  int get_x() const { return x; }
                  void set_y(const int param) {
                  y = param;
                  calculate();
                  }
                  int get_y() const { return y; }
                  int get_z() const { return z; }
                  };

                  istream& operator >>(istream& lhs, foo& rhs) {
                  lhs >> rhs.x >> rhs.y;
                  rhs.calculate();
                  return lhs;
                  }


                  This will recalculate z each time x or y is set. This is a good solution if you access z frequently, and x and y are set infrequently. If x and y are set frequently or calculate is expensive you might consider:



                  class foo {
                  int x;
                  int y;
                  int z;
                  bool dirty;
                  void calculate() { z = (x + y) / 2; }
                  friend istream& operator >>(istream& lhs, foo& rhs);
                  public:
                  void set_x(const int param) {
                  x = param;
                  dirty = true;
                  }
                  int get_x() const { return x; }
                  void set_y(const int param) {
                  y = param;
                  dirty = true;
                  }
                  int get_y() const { return y; }
                  int get_z() const {
                  if(dirty) {
                  calculate();
                  }
                  return z;
                  }
                  };

                  istream& operator >>(istream& lhs, foo& rhs) {
                  lhs >> rhs.x >> rhs.y;
                  rhs.dirty = true;
                  return lhs;
                  }


                  Note that I've included an extraction operator, so whichever you choose your code can turn into something as simple as:



                  foo xyz;

                  cin >> xyz;
                  cout << xyz.get_z();





                  share|improve this answer
























                  • I don't quite understand how lambda work. But if you've played dota you'd know how gold in the game work. The way it is displayed all the time and adding 1 gold every split-second. I'm asking this question with that in mind. How do I implement that in c++?

                    – Michael D. Blake
                    Mar 29 at 18:47






                  • 2





                    @NayWunnaZaw I mean generally you're going to have a main class which calls the tick function on any class that needs live updating, passing in a time elapsed since last tick parameter. You'd probably have a player class instead of just the simple foo which would do loads of things. Like the player class's tick would need to update the damage of poison effects, calculate cooldown times, and also calculate gold. I recognize this is probably a gross over simplification. But I do think you're going to want to go with a class here.

                    – Jonathan Mee
                    Mar 29 at 18:58











                  • thanks for that, but I like lambda answer more for it's simplicity for a variable. and that fits my question. And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there.

                    – Michael D. Blake
                    Mar 29 at 19:10











                  • @MichaelD.Blake There are always lots of solutions to a problem; as the actual programmer you are always in the best place to make that decision. But I do have some concerns as the statement: "And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there." That's the point of the class... it only calculates when required. The lambda will calculate every time you call it... Which is potentially very wasteful... But both the class and the lambda are wasteful if you're only finding z once. Is that where you're at?

                    – Jonathan Mee
                    Apr 4 at 12:38














                  4












                  4








                  4







                  So a big problem that I see with the lambda solutions provided is that z is calculated each time that it is inspected even if neither x nor y has changed. To get around this you really need to link these variables.
                  I would suggest doing that via class:



                  class foo {
                  int x;
                  int y;
                  int z;
                  void calculate() { z = (x + y) / 2; }
                  friend istream& operator >>(istream& lhs, foo& rhs);
                  public:
                  void set_x(const int param) {
                  x = param;
                  calculate();
                  }
                  int get_x() const { return x; }
                  void set_y(const int param) {
                  y = param;
                  calculate();
                  }
                  int get_y() const { return y; }
                  int get_z() const { return z; }
                  };

                  istream& operator >>(istream& lhs, foo& rhs) {
                  lhs >> rhs.x >> rhs.y;
                  rhs.calculate();
                  return lhs;
                  }


                  This will recalculate z each time x or y is set. This is a good solution if you access z frequently, and x and y are set infrequently. If x and y are set frequently or calculate is expensive you might consider:



                  class foo {
                  int x;
                  int y;
                  int z;
                  bool dirty;
                  void calculate() { z = (x + y) / 2; }
                  friend istream& operator >>(istream& lhs, foo& rhs);
                  public:
                  void set_x(const int param) {
                  x = param;
                  dirty = true;
                  }
                  int get_x() const { return x; }
                  void set_y(const int param) {
                  y = param;
                  dirty = true;
                  }
                  int get_y() const { return y; }
                  int get_z() const {
                  if(dirty) {
                  calculate();
                  }
                  return z;
                  }
                  };

                  istream& operator >>(istream& lhs, foo& rhs) {
                  lhs >> rhs.x >> rhs.y;
                  rhs.dirty = true;
                  return lhs;
                  }


                  Note that I've included an extraction operator, so whichever you choose your code can turn into something as simple as:



                  foo xyz;

                  cin >> xyz;
                  cout << xyz.get_z();





                  share|improve this answer













                  So a big problem that I see with the lambda solutions provided is that z is calculated each time that it is inspected even if neither x nor y has changed. To get around this you really need to link these variables.
                  I would suggest doing that via class:



                  class foo {
                  int x;
                  int y;
                  int z;
                  void calculate() { z = (x + y) / 2; }
                  friend istream& operator >>(istream& lhs, foo& rhs);
                  public:
                  void set_x(const int param) {
                  x = param;
                  calculate();
                  }
                  int get_x() const { return x; }
                  void set_y(const int param) {
                  y = param;
                  calculate();
                  }
                  int get_y() const { return y; }
                  int get_z() const { return z; }
                  };

                  istream& operator >>(istream& lhs, foo& rhs) {
                  lhs >> rhs.x >> rhs.y;
                  rhs.calculate();
                  return lhs;
                  }


                  This will recalculate z each time x or y is set. This is a good solution if you access z frequently, and x and y are set infrequently. If x and y are set frequently or calculate is expensive you might consider:



                  class foo {
                  int x;
                  int y;
                  int z;
                  bool dirty;
                  void calculate() { z = (x + y) / 2; }
                  friend istream& operator >>(istream& lhs, foo& rhs);
                  public:
                  void set_x(const int param) {
                  x = param;
                  dirty = true;
                  }
                  int get_x() const { return x; }
                  void set_y(const int param) {
                  y = param;
                  dirty = true;
                  }
                  int get_y() const { return y; }
                  int get_z() const {
                  if(dirty) {
                  calculate();
                  }
                  return z;
                  }
                  };

                  istream& operator >>(istream& lhs, foo& rhs) {
                  lhs >> rhs.x >> rhs.y;
                  rhs.dirty = true;
                  return lhs;
                  }


                  Note that I've included an extraction operator, so whichever you choose your code can turn into something as simple as:



                  foo xyz;

                  cin >> xyz;
                  cout << xyz.get_z();






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 29 at 17:42









                  Jonathan MeeJonathan Mee

                  22.1k1066176




                  22.1k1066176













                  • I don't quite understand how lambda work. But if you've played dota you'd know how gold in the game work. The way it is displayed all the time and adding 1 gold every split-second. I'm asking this question with that in mind. How do I implement that in c++?

                    – Michael D. Blake
                    Mar 29 at 18:47






                  • 2





                    @NayWunnaZaw I mean generally you're going to have a main class which calls the tick function on any class that needs live updating, passing in a time elapsed since last tick parameter. You'd probably have a player class instead of just the simple foo which would do loads of things. Like the player class's tick would need to update the damage of poison effects, calculate cooldown times, and also calculate gold. I recognize this is probably a gross over simplification. But I do think you're going to want to go with a class here.

                    – Jonathan Mee
                    Mar 29 at 18:58











                  • thanks for that, but I like lambda answer more for it's simplicity for a variable. and that fits my question. And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there.

                    – Michael D. Blake
                    Mar 29 at 19:10











                  • @MichaelD.Blake There are always lots of solutions to a problem; as the actual programmer you are always in the best place to make that decision. But I do have some concerns as the statement: "And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there." That's the point of the class... it only calculates when required. The lambda will calculate every time you call it... Which is potentially very wasteful... But both the class and the lambda are wasteful if you're only finding z once. Is that where you're at?

                    – Jonathan Mee
                    Apr 4 at 12:38



















                  • I don't quite understand how lambda work. But if you've played dota you'd know how gold in the game work. The way it is displayed all the time and adding 1 gold every split-second. I'm asking this question with that in mind. How do I implement that in c++?

                    – Michael D. Blake
                    Mar 29 at 18:47






                  • 2





                    @NayWunnaZaw I mean generally you're going to have a main class which calls the tick function on any class that needs live updating, passing in a time elapsed since last tick parameter. You'd probably have a player class instead of just the simple foo which would do loads of things. Like the player class's tick would need to update the damage of poison effects, calculate cooldown times, and also calculate gold. I recognize this is probably a gross over simplification. But I do think you're going to want to go with a class here.

                    – Jonathan Mee
                    Mar 29 at 18:58











                  • thanks for that, but I like lambda answer more for it's simplicity for a variable. and that fits my question. And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there.

                    – Michael D. Blake
                    Mar 29 at 19:10











                  • @MichaelD.Blake There are always lots of solutions to a problem; as the actual programmer you are always in the best place to make that decision. But I do have some concerns as the statement: "And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there." That's the point of the class... it only calculates when required. The lambda will calculate every time you call it... Which is potentially very wasteful... But both the class and the lambda are wasteful if you're only finding z once. Is that where you're at?

                    – Jonathan Mee
                    Apr 4 at 12:38

















                  I don't quite understand how lambda work. But if you've played dota you'd know how gold in the game work. The way it is displayed all the time and adding 1 gold every split-second. I'm asking this question with that in mind. How do I implement that in c++?

                  – Michael D. Blake
                  Mar 29 at 18:47





                  I don't quite understand how lambda work. But if you've played dota you'd know how gold in the game work. The way it is displayed all the time and adding 1 gold every split-second. I'm asking this question with that in mind. How do I implement that in c++?

                  – Michael D. Blake
                  Mar 29 at 18:47




                  2




                  2





                  @NayWunnaZaw I mean generally you're going to have a main class which calls the tick function on any class that needs live updating, passing in a time elapsed since last tick parameter. You'd probably have a player class instead of just the simple foo which would do loads of things. Like the player class's tick would need to update the damage of poison effects, calculate cooldown times, and also calculate gold. I recognize this is probably a gross over simplification. But I do think you're going to want to go with a class here.

                  – Jonathan Mee
                  Mar 29 at 18:58





                  @NayWunnaZaw I mean generally you're going to have a main class which calls the tick function on any class that needs live updating, passing in a time elapsed since last tick parameter. You'd probably have a player class instead of just the simple foo which would do loads of things. Like the player class's tick would need to update the damage of poison effects, calculate cooldown times, and also calculate gold. I recognize this is probably a gross over simplification. But I do think you're going to want to go with a class here.

                  – Jonathan Mee
                  Mar 29 at 18:58













                  thanks for that, but I like lambda answer more for it's simplicity for a variable. and that fits my question. And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there.

                  – Michael D. Blake
                  Mar 29 at 19:10





                  thanks for that, but I like lambda answer more for it's simplicity for a variable. and that fits my question. And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there.

                  – Michael D. Blake
                  Mar 29 at 19:10













                  @MichaelD.Blake There are always lots of solutions to a problem; as the actual programmer you are always in the best place to make that decision. But I do have some concerns as the statement: "And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there." That's the point of the class... it only calculates when required. The lambda will calculate every time you call it... Which is potentially very wasteful... But both the class and the lambda are wasteful if you're only finding z once. Is that where you're at?

                  – Jonathan Mee
                  Apr 4 at 12:38





                  @MichaelD.Blake There are always lots of solutions to a problem; as the actual programmer you are always in the best place to make that decision. But I do have some concerns as the statement: "And class type solution should be used instead if we plan on using the equation more than once like shadowranger said up there." That's the point of the class... it only calculates when required. The lambda will calculate every time you call it... Which is potentially very wasteful... But both the class and the lambda are wasteful if you're only finding z once. Is that where you're at?

                  – Jonathan Mee
                  Apr 4 at 12:38











                  2














                  You can get what you're asking for by using macros:



                  {
                  int x, y;
                  #define z (x + y)
                  /* use x, y, z */
                  #undef z
                  }


                  The #undef is for a little sanity. For more sanity, don't use macros at all, and go with one of the other answers, and deal with the extra verbosity.



                  Although a class with a custom operator int would work in a lot of cases ... hmm.






                  share|improve this answer



















                  • 1





                    Although this could use an EXTREME CAUTION warning, I think it is worth mentioning. Sometimes quick'n'dirty is called for. I have used tricks like this to save time in programming competitions, or in mindless repetitive matrix calculations that would be a lot more verbose and/or bug-prone using any other approach.

                    – Artelius
                    Mar 29 at 7:13


















                  2














                  You can get what you're asking for by using macros:



                  {
                  int x, y;
                  #define z (x + y)
                  /* use x, y, z */
                  #undef z
                  }


                  The #undef is for a little sanity. For more sanity, don't use macros at all, and go with one of the other answers, and deal with the extra verbosity.



                  Although a class with a custom operator int would work in a lot of cases ... hmm.






                  share|improve this answer



















                  • 1





                    Although this could use an EXTREME CAUTION warning, I think it is worth mentioning. Sometimes quick'n'dirty is called for. I have used tricks like this to save time in programming competitions, or in mindless repetitive matrix calculations that would be a lot more verbose and/or bug-prone using any other approach.

                    – Artelius
                    Mar 29 at 7:13
















                  2












                  2








                  2







                  You can get what you're asking for by using macros:



                  {
                  int x, y;
                  #define z (x + y)
                  /* use x, y, z */
                  #undef z
                  }


                  The #undef is for a little sanity. For more sanity, don't use macros at all, and go with one of the other answers, and deal with the extra verbosity.



                  Although a class with a custom operator int would work in a lot of cases ... hmm.






                  share|improve this answer













                  You can get what you're asking for by using macros:



                  {
                  int x, y;
                  #define z (x + y)
                  /* use x, y, z */
                  #undef z
                  }


                  The #undef is for a little sanity. For more sanity, don't use macros at all, and go with one of the other answers, and deal with the extra verbosity.



                  Although a class with a custom operator int would work in a lot of cases ... hmm.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 29 at 2:40









                  o11co11c

                  11k43155




                  11k43155








                  • 1





                    Although this could use an EXTREME CAUTION warning, I think it is worth mentioning. Sometimes quick'n'dirty is called for. I have used tricks like this to save time in programming competitions, or in mindless repetitive matrix calculations that would be a lot more verbose and/or bug-prone using any other approach.

                    – Artelius
                    Mar 29 at 7:13
















                  • 1





                    Although this could use an EXTREME CAUTION warning, I think it is worth mentioning. Sometimes quick'n'dirty is called for. I have used tricks like this to save time in programming competitions, or in mindless repetitive matrix calculations that would be a lot more verbose and/or bug-prone using any other approach.

                    – Artelius
                    Mar 29 at 7:13










                  1




                  1





                  Although this could use an EXTREME CAUTION warning, I think it is worth mentioning. Sometimes quick'n'dirty is called for. I have used tricks like this to save time in programming competitions, or in mindless repetitive matrix calculations that would be a lot more verbose and/or bug-prone using any other approach.

                  – Artelius
                  Mar 29 at 7:13







                  Although this could use an EXTREME CAUTION warning, I think it is worth mentioning. Sometimes quick'n'dirty is called for. I have used tricks like this to save time in programming competitions, or in mindless repetitive matrix calculations that would be a lot more verbose and/or bug-prone using any other approach.

                  – Artelius
                  Mar 29 at 7:13













                  2














                  What you're describing is late binding, which a compiled language like C++ can do only with difficulty. In an interpreted language, all you need is the ability to set z to an unevaluated expression and delay binding of z's value until the calculation is needed, typically signaled by a call to a function that forces the evaluation such as eval in Lisp. In my Expert System's rules language, I have not only eval but noeval, which protects its argument from one level of evaluation. That provides granular control over the binding, with some sub-expressions being evaluated (bound) and others not, if desired. This is not applicable to your scenario, but it sets the scene in terms of the language landscape.






                  share|improve this answer




























                    2














                    What you're describing is late binding, which a compiled language like C++ can do only with difficulty. In an interpreted language, all you need is the ability to set z to an unevaluated expression and delay binding of z's value until the calculation is needed, typically signaled by a call to a function that forces the evaluation such as eval in Lisp. In my Expert System's rules language, I have not only eval but noeval, which protects its argument from one level of evaluation. That provides granular control over the binding, with some sub-expressions being evaluated (bound) and others not, if desired. This is not applicable to your scenario, but it sets the scene in terms of the language landscape.






                    share|improve this answer


























                      2












                      2








                      2







                      What you're describing is late binding, which a compiled language like C++ can do only with difficulty. In an interpreted language, all you need is the ability to set z to an unevaluated expression and delay binding of z's value until the calculation is needed, typically signaled by a call to a function that forces the evaluation such as eval in Lisp. In my Expert System's rules language, I have not only eval but noeval, which protects its argument from one level of evaluation. That provides granular control over the binding, with some sub-expressions being evaluated (bound) and others not, if desired. This is not applicable to your scenario, but it sets the scene in terms of the language landscape.






                      share|improve this answer













                      What you're describing is late binding, which a compiled language like C++ can do only with difficulty. In an interpreted language, all you need is the ability to set z to an unevaluated expression and delay binding of z's value until the calculation is needed, typically signaled by a call to a function that forces the evaluation such as eval in Lisp. In my Expert System's rules language, I have not only eval but noeval, which protects its argument from one level of evaluation. That provides granular control over the binding, with some sub-expressions being evaluated (bound) and others not, if desired. This is not applicable to your scenario, but it sets the scene in terms of the language landscape.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Apr 2 at 17:53









                      Stephen F. HeffnerStephen F. Heffner

                      12613




                      12613























                          2














                          You could write a class that encapsulates its state to update either when mutated or return the right result when requested :



                          #include <iostream>

                          template<typename T, typename U, typename V>
                          class DynamicCalc
                          {
                          public:
                          DynamicCalc(const T& func, const U& memberOne, const V& memberTwo) :
                          _func(func)
                          , _memberOne(memberOne)
                          , _memberTwo(memberTwo)
                          {

                          }

                          void SetMemberOne(const U& memberOne) { _memberOne = memberOne; }
                          void SetMemberTwo(const U& memberTwo) { _memberTwo = memberTwo; }
                          auto Retrieve() { return _func(_memberOne, _memberTwo); }

                          U GetMemberOne() { return _memberOne; }
                          V GetMemberTwo() { return _memberTwo; }

                          private:
                          T _func;

                          U _memberOne;
                          V _memberTwo;
                          };

                          int main() {

                          auto func = (int x, int y) {
                          return x + y;
                          };
                          DynamicCalc<decltype(func), int, int> c(func, 3, 5);

                          c.SetMemberOne(5);
                          std::cout << c.Retrieve();
                          }


                          In truth, if you're happy for the calculation to happen when the value is reuqested then the getters/setters are unnecessary.






                          share|improve this answer






























                            2














                            You could write a class that encapsulates its state to update either when mutated or return the right result when requested :



                            #include <iostream>

                            template<typename T, typename U, typename V>
                            class DynamicCalc
                            {
                            public:
                            DynamicCalc(const T& func, const U& memberOne, const V& memberTwo) :
                            _func(func)
                            , _memberOne(memberOne)
                            , _memberTwo(memberTwo)
                            {

                            }

                            void SetMemberOne(const U& memberOne) { _memberOne = memberOne; }
                            void SetMemberTwo(const U& memberTwo) { _memberTwo = memberTwo; }
                            auto Retrieve() { return _func(_memberOne, _memberTwo); }

                            U GetMemberOne() { return _memberOne; }
                            V GetMemberTwo() { return _memberTwo; }

                            private:
                            T _func;

                            U _memberOne;
                            V _memberTwo;
                            };

                            int main() {

                            auto func = (int x, int y) {
                            return x + y;
                            };
                            DynamicCalc<decltype(func), int, int> c(func, 3, 5);

                            c.SetMemberOne(5);
                            std::cout << c.Retrieve();
                            }


                            In truth, if you're happy for the calculation to happen when the value is reuqested then the getters/setters are unnecessary.






                            share|improve this answer




























                              2












                              2








                              2







                              You could write a class that encapsulates its state to update either when mutated or return the right result when requested :



                              #include <iostream>

                              template<typename T, typename U, typename V>
                              class DynamicCalc
                              {
                              public:
                              DynamicCalc(const T& func, const U& memberOne, const V& memberTwo) :
                              _func(func)
                              , _memberOne(memberOne)
                              , _memberTwo(memberTwo)
                              {

                              }

                              void SetMemberOne(const U& memberOne) { _memberOne = memberOne; }
                              void SetMemberTwo(const U& memberTwo) { _memberTwo = memberTwo; }
                              auto Retrieve() { return _func(_memberOne, _memberTwo); }

                              U GetMemberOne() { return _memberOne; }
                              V GetMemberTwo() { return _memberTwo; }

                              private:
                              T _func;

                              U _memberOne;
                              V _memberTwo;
                              };

                              int main() {

                              auto func = (int x, int y) {
                              return x + y;
                              };
                              DynamicCalc<decltype(func), int, int> c(func, 3, 5);

                              c.SetMemberOne(5);
                              std::cout << c.Retrieve();
                              }


                              In truth, if you're happy for the calculation to happen when the value is reuqested then the getters/setters are unnecessary.






                              share|improve this answer















                              You could write a class that encapsulates its state to update either when mutated or return the right result when requested :



                              #include <iostream>

                              template<typename T, typename U, typename V>
                              class DynamicCalc
                              {
                              public:
                              DynamicCalc(const T& func, const U& memberOne, const V& memberTwo) :
                              _func(func)
                              , _memberOne(memberOne)
                              , _memberTwo(memberTwo)
                              {

                              }

                              void SetMemberOne(const U& memberOne) { _memberOne = memberOne; }
                              void SetMemberTwo(const U& memberTwo) { _memberTwo = memberTwo; }
                              auto Retrieve() { return _func(_memberOne, _memberTwo); }

                              U GetMemberOne() { return _memberOne; }
                              V GetMemberTwo() { return _memberTwo; }

                              private:
                              T _func;

                              U _memberOne;
                              V _memberTwo;
                              };

                              int main() {

                              auto func = (int x, int y) {
                              return x + y;
                              };
                              DynamicCalc<decltype(func), int, int> c(func, 3, 5);

                              c.SetMemberOne(5);
                              std::cout << c.Retrieve();
                              }


                              In truth, if you're happy for the calculation to happen when the value is reuqested then the getters/setters are unnecessary.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Apr 4 at 8:46

























                              answered Mar 28 at 17:00









                              GeorgeGeorge

                              1,6081720




                              1,6081720























                                  0














                                  Ok, let me at last write the right and only true answer to your stated question:



                                  You can't.



                                  You can't write z = x + y and then have all the code using z magically re-run whenever x or y changes.



                                  So what can be done?



                                  As mentioned in other answers, there are several patterns to express that you want changes of x and y to cause some updates, but in any case you need these updates to happen more or less explicitly.



                                  Depending on a use case, you may:





                                  • Have the value recomputed anyway at all times this matters. E.g. if you write a game and redraw the screen every frame, then likely just making sure that you don't accidentally keep the z value between the frames is enough. Be aware of when your value can change and when it can't. Whether you use a function, a lambda, a class method, or just repeat the expression, is mostly esthetical decision. If available, this is the best approach, because it is fully transparent.



                                    For instance, in racing game you'd likely update your current speed at the beginning of the new tick computation, and then use the updated value when computing your car's movement, when redrawing the speed indicator, when creating the motion blur, and so on. You don't need any magic and not even a function, you can just use a variable, because you know your speed won't change during one frame.



                                  • Call the update explicitly. Use it e.g. when you have a single widget you need to update. Downside is that you need to remember to call the update, which is somewhat brittle, but on the upside - it is dead simple. A middle ground is to have the update call integrated with a setter, making it kind of poor man's Observer implementation.


                                  • Use Observer pattern (see also signals and slots, this is one way of implementing Observer). Use it e.g. when you have many widgets to update, or you create them dynamically. Avoid using it when one of the above works, they are way simpler.


                                  • Use dedicated reactive programming library. As such stuff exists, I feel obliged to mention it. However, I honestly don't see any application where I would use it. It mostly seems like a complicated way to shoot your feet. The implicit updates are going to backfire, and you'll have to rewrite everything. Just don't, not in C++. What is important: while this approach is closest to "magically update everything", it would impose constraints on how you write your code, and eventually you'll get one of the above solutions, just more complicated.







                                  share|improve this answer






























                                    0














                                    Ok, let me at last write the right and only true answer to your stated question:



                                    You can't.



                                    You can't write z = x + y and then have all the code using z magically re-run whenever x or y changes.



                                    So what can be done?



                                    As mentioned in other answers, there are several patterns to express that you want changes of x and y to cause some updates, but in any case you need these updates to happen more or less explicitly.



                                    Depending on a use case, you may:





                                    • Have the value recomputed anyway at all times this matters. E.g. if you write a game and redraw the screen every frame, then likely just making sure that you don't accidentally keep the z value between the frames is enough. Be aware of when your value can change and when it can't. Whether you use a function, a lambda, a class method, or just repeat the expression, is mostly esthetical decision. If available, this is the best approach, because it is fully transparent.



                                      For instance, in racing game you'd likely update your current speed at the beginning of the new tick computation, and then use the updated value when computing your car's movement, when redrawing the speed indicator, when creating the motion blur, and so on. You don't need any magic and not even a function, you can just use a variable, because you know your speed won't change during one frame.



                                    • Call the update explicitly. Use it e.g. when you have a single widget you need to update. Downside is that you need to remember to call the update, which is somewhat brittle, but on the upside - it is dead simple. A middle ground is to have the update call integrated with a setter, making it kind of poor man's Observer implementation.


                                    • Use Observer pattern (see also signals and slots, this is one way of implementing Observer). Use it e.g. when you have many widgets to update, or you create them dynamically. Avoid using it when one of the above works, they are way simpler.


                                    • Use dedicated reactive programming library. As such stuff exists, I feel obliged to mention it. However, I honestly don't see any application where I would use it. It mostly seems like a complicated way to shoot your feet. The implicit updates are going to backfire, and you'll have to rewrite everything. Just don't, not in C++. What is important: while this approach is closest to "magically update everything", it would impose constraints on how you write your code, and eventually you'll get one of the above solutions, just more complicated.







                                    share|improve this answer




























                                      0












                                      0








                                      0







                                      Ok, let me at last write the right and only true answer to your stated question:



                                      You can't.



                                      You can't write z = x + y and then have all the code using z magically re-run whenever x or y changes.



                                      So what can be done?



                                      As mentioned in other answers, there are several patterns to express that you want changes of x and y to cause some updates, but in any case you need these updates to happen more or less explicitly.



                                      Depending on a use case, you may:





                                      • Have the value recomputed anyway at all times this matters. E.g. if you write a game and redraw the screen every frame, then likely just making sure that you don't accidentally keep the z value between the frames is enough. Be aware of when your value can change and when it can't. Whether you use a function, a lambda, a class method, or just repeat the expression, is mostly esthetical decision. If available, this is the best approach, because it is fully transparent.



                                        For instance, in racing game you'd likely update your current speed at the beginning of the new tick computation, and then use the updated value when computing your car's movement, when redrawing the speed indicator, when creating the motion blur, and so on. You don't need any magic and not even a function, you can just use a variable, because you know your speed won't change during one frame.



                                      • Call the update explicitly. Use it e.g. when you have a single widget you need to update. Downside is that you need to remember to call the update, which is somewhat brittle, but on the upside - it is dead simple. A middle ground is to have the update call integrated with a setter, making it kind of poor man's Observer implementation.


                                      • Use Observer pattern (see also signals and slots, this is one way of implementing Observer). Use it e.g. when you have many widgets to update, or you create them dynamically. Avoid using it when one of the above works, they are way simpler.


                                      • Use dedicated reactive programming library. As such stuff exists, I feel obliged to mention it. However, I honestly don't see any application where I would use it. It mostly seems like a complicated way to shoot your feet. The implicit updates are going to backfire, and you'll have to rewrite everything. Just don't, not in C++. What is important: while this approach is closest to "magically update everything", it would impose constraints on how you write your code, and eventually you'll get one of the above solutions, just more complicated.







                                      share|improve this answer















                                      Ok, let me at last write the right and only true answer to your stated question:



                                      You can't.



                                      You can't write z = x + y and then have all the code using z magically re-run whenever x or y changes.



                                      So what can be done?



                                      As mentioned in other answers, there are several patterns to express that you want changes of x and y to cause some updates, but in any case you need these updates to happen more or less explicitly.



                                      Depending on a use case, you may:





                                      • Have the value recomputed anyway at all times this matters. E.g. if you write a game and redraw the screen every frame, then likely just making sure that you don't accidentally keep the z value between the frames is enough. Be aware of when your value can change and when it can't. Whether you use a function, a lambda, a class method, or just repeat the expression, is mostly esthetical decision. If available, this is the best approach, because it is fully transparent.



                                        For instance, in racing game you'd likely update your current speed at the beginning of the new tick computation, and then use the updated value when computing your car's movement, when redrawing the speed indicator, when creating the motion blur, and so on. You don't need any magic and not even a function, you can just use a variable, because you know your speed won't change during one frame.



                                      • Call the update explicitly. Use it e.g. when you have a single widget you need to update. Downside is that you need to remember to call the update, which is somewhat brittle, but on the upside - it is dead simple. A middle ground is to have the update call integrated with a setter, making it kind of poor man's Observer implementation.


                                      • Use Observer pattern (see also signals and slots, this is one way of implementing Observer). Use it e.g. when you have many widgets to update, or you create them dynamically. Avoid using it when one of the above works, they are way simpler.


                                      • Use dedicated reactive programming library. As such stuff exists, I feel obliged to mention it. However, I honestly don't see any application where I would use it. It mostly seems like a complicated way to shoot your feet. The implicit updates are going to backfire, and you'll have to rewrite everything. Just don't, not in C++. What is important: while this approach is closest to "magically update everything", it would impose constraints on how you write your code, and eventually you'll get one of the above solutions, just more complicated.








                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Apr 4 at 6:29









                                      Aconcagua

                                      13.5k32445




                                      13.5k32445










                                      answered Apr 3 at 5:20









                                      FraxFrax

                                      1,365714




                                      1,365714






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55402807%2fhow-can-i-make-a-variable-always-equal-to-the-result-of-some-calculations%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                                          Alcedinidae

                                          Origin of the phrase “under your belt”?