How do I make a variable always equal to the result of some calculations? The Next CEO of Stack OverflowLazy evaluation in C++Convention for leaving body of an if/else blankHow do you clear a stringstream variable?What's the best way to do fixed-point math?Is the sizeof(some pointer) always equal to four?How to make a SIMPLE C++ Makefile?Is there some ninja trick to make a variable constant after its declaration?How to make my custom type to work with “range-based for loops”?Does static constexpr variable make sense?How to make a conditional typedef in C++QTableView slow scrolling when many cells are visible at onceC++11 Print run-time variable name equal to some constexpr variable

sp_blitzCache results Memory grants

If a black hole is created from light, can this black hole then move at speed of light?

How did people program for Consoles with multiple CPUs?

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

Which tube will fit a -(700 x 25c) wheel?

MessageLevel in QGIS3

Is micro rebar a better way to reinforce concrete than rebar?

Return the Closest Prime Number

RegionPlot of annulus gives a mesh

How do I transpose the 1st and -1th levels of an arbitrarily nested array?

Is there a way to save my career from absolute disaster?

What flight has the highest ratio of time difference to flight time?

Limits on contract work without pre-agreed price/contract (UK)

Won the lottery - how do I keep the money?

How to solve a differential equation with a term to a power?

Why has the US not been more assertive in confronting Russia in recent years?

How did the Bene Gesserit know how to make a Kwisatz Haderach?

Why am I allowed to create multiple unique pointers from a single object?

Is there a difference between "Fahrstuhl" and "Aufzug"

WOW air has ceased operation, can I get my tickets refunded?

What does "Its cash flow is deeply negative" mean?

Would a completely good Muggle be able to use a wand?

What is "(CFMCC)" on an ILS approach chart?

What is the purpose of the Evocation wizard's Potent Cantrip feature?



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



The Next CEO of Stack OverflowLazy evaluation in C++Convention for leaving body of an if/else blankHow do you clear a stringstream variable?What's the best way to do fixed-point math?Is the sizeof(some pointer) always equal to four?How to make a SIMPLE C++ Makefile?Is there some ninja trick to make a variable constant after its declaration?How to make my custom type to work with “range-based for loops”?Does static constexpr variable make sense?How to make a conditional typedef in C++QTableView slow scrolling when many cells are visible at onceC++11 Print run-time variable name equal to some constexpr variable










26















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 zx + 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









New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 2





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

    – Pete Becker
    yesterday






  • 2





    @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.

    – Nay Wunna Zaw
    yesterday






  • 19





    @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
    yesterday






  • 34





    That's called a "function."

    – ApproachingDarknessFish
    yesterday






  • 2





    @Nat: This is something GMP's C++ interface does; operators produce progressively more complex expression trees until assigned to mpz_class, at which point the expression tree is evaluated to produce the final result. It allows expressions like a += b * c; to collapse to (ignoring accessor functions involved) mpz_addmul(a, b, c) (which is an optimized one-operation version of the above), rather than creating a temporary t and do mpz_mul(t, b, c) followed by mpz_add(a, a, t) followed by cleaning t. It's a production version of this.

    – ShadowRanger
    9 hours ago















26















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 zx + 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









New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 2





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

    – Pete Becker
    yesterday






  • 2





    @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.

    – Nay Wunna Zaw
    yesterday






  • 19





    @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
    yesterday






  • 34





    That's called a "function."

    – ApproachingDarknessFish
    yesterday






  • 2





    @Nat: This is something GMP's C++ interface does; operators produce progressively more complex expression trees until assigned to mpz_class, at which point the expression tree is evaluated to produce the final result. It allows expressions like a += b * c; to collapse to (ignoring accessor functions involved) mpz_addmul(a, b, c) (which is an optimized one-operation version of the above), rather than creating a temporary t and do mpz_mul(t, b, c) followed by mpz_add(a, a, t) followed by cleaning t. It's a production version of this.

    – ShadowRanger
    9 hours ago













26












26








26


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 zx + 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









New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












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 zx + 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









New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 1 hour ago









Peter Mortensen

13.8k1987113




13.8k1987113






New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









Nay Wunna ZawNay Wunna Zaw

138211




138211




New contributor




Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Nay Wunna Zaw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 2





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

    – Pete Becker
    yesterday






  • 2





    @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.

    – Nay Wunna Zaw
    yesterday






  • 19





    @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
    yesterday






  • 34





    That's called a "function."

    – ApproachingDarknessFish
    yesterday






  • 2





    @Nat: This is something GMP's C++ interface does; operators produce progressively more complex expression trees until assigned to mpz_class, at which point the expression tree is evaluated to produce the final result. It allows expressions like a += b * c; to collapse to (ignoring accessor functions involved) mpz_addmul(a, b, c) (which is an optimized one-operation version of the above), rather than creating a temporary t and do mpz_mul(t, b, c) followed by mpz_add(a, a, t) followed by cleaning t. It's a production version of this.

    – ShadowRanger
    9 hours ago












  • 2





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

    – Pete Becker
    yesterday






  • 2





    @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.

    – Nay Wunna Zaw
    yesterday






  • 19





    @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
    yesterday






  • 34





    That's called a "function."

    – ApproachingDarknessFish
    yesterday






  • 2





    @Nat: This is something GMP's C++ interface does; operators produce progressively more complex expression trees until assigned to mpz_class, at which point the expression tree is evaluated to produce the final result. It allows expressions like a += b * c; to collapse to (ignoring accessor functions involved) mpz_addmul(a, b, c) (which is an optimized one-operation version of the above), rather than creating a temporary t and do mpz_mul(t, b, c) followed by mpz_add(a, a, t) followed by cleaning t. It's a production version of this.

    – ShadowRanger
    9 hours ago







2




2





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

– Pete Becker
yesterday





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

– Pete Becker
yesterday




2




2





@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.

– Nay Wunna Zaw
yesterday





@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.

– Nay Wunna Zaw
yesterday




19




19





@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
yesterday





@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
yesterday




34




34





That's called a "function."

– ApproachingDarknessFish
yesterday





That's called a "function."

– ApproachingDarknessFish
yesterday




2




2





@Nat: This is something GMP's C++ interface does; operators produce progressively more complex expression trees until assigned to mpz_class, at which point the expression tree is evaluated to produce the final result. It allows expressions like a += b * c; to collapse to (ignoring accessor functions involved) mpz_addmul(a, b, c) (which is an optimized one-operation version of the above), rather than creating a temporary t and do mpz_mul(t, b, c) followed by mpz_add(a, a, t) followed by cleaning t. It's a production version of this.

– ShadowRanger
9 hours ago





@Nat: This is something GMP's C++ interface does; operators produce progressively more complex expression trees until assigned to mpz_class, at which point the expression tree is evaluated to produce the final result. It allows expressions like a += b * c; to collapse to (ignoring accessor functions involved) mpz_addmul(a, b, c) (which is an optimized one-operation version of the above), rather than creating a temporary t and do mpz_mul(t, b, c) followed by mpz_add(a, a, t) followed by cleaning t. It's a production version of this.

– ShadowRanger
9 hours ago












9 Answers
9






active

oldest

votes


















32














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 zx + 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 = [&]() y != cache_y)

cache_x = x;
cache_y = y;
cache_result = x + y;

return cache_result;
;





share|improve this answer




















  • 1





    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
    yesterday






  • 6





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

    – Mooing Duck
    yesterday











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

    – Fabio Turati
    yesterday











  • @FabioTurati See Aconcagua's answer

    – NathanOliver
    yesterday






  • 6





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

    – Mehrdad
    19 hours ago



















24














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;





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.

    – Nay Wunna Zaw
    11 hours ago






  • 2





    @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
    9 hours ago











  • @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.

    – Nay Wunna Zaw
    7 hours ago






  • 2





    @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
    6 hours ago



















19














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






























    10














    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

























    • 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
      16 hours ago






    • 1





      @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
      13 hours ago


















    4














    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?

      – Nay Wunna Zaw
      12 hours ago











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

      – Peter Mortensen
      17 mins ago


















    3














    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 zx + 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?

      – Nay Wunna Zaw
      yesterday











    • @NayWunnaZaw, yes, that is correct.

      – R Sahu
      yesterday






    • 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
      yesterday






    • 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
      yesterday


















    2














    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
      yesterday











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

      – Hiroki
      yesterday












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

      – Hiroki
      16 hours ago







    • 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
      16 hours ago











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

      – Hiroki
      5 hours ago


















    1














    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++?

      – Nay Wunna Zaw
      7 hours ago






    • 1





      @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
      7 hours ago











    • 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.

      – Nay Wunna Zaw
      6 hours ago


















    0














    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























    • 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
      18 hours ago












    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
    );



    );






    Nay Wunna Zaw is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















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

    );

    Post as a guest















    Required, but never shown

























    9 Answers
    9






    active

    oldest

    votes








    9 Answers
    9






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    32














    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 zx + 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 = [&]() y != cache_y)

    cache_x = x;
    cache_y = y;
    cache_result = x + y;

    return cache_result;
    ;





    share|improve this answer




















    • 1





      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
      yesterday






    • 6





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

      – Mooing Duck
      yesterday











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

      – Fabio Turati
      yesterday











    • @FabioTurati See Aconcagua's answer

      – NathanOliver
      yesterday






    • 6





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

      – Mehrdad
      19 hours ago
















    32














    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 zx + 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 = [&]() y != cache_y)

    cache_x = x;
    cache_y = y;
    cache_result = x + y;

    return cache_result;
    ;





    share|improve this answer




















    • 1





      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
      yesterday






    • 6





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

      – Mooing Duck
      yesterday











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

      – Fabio Turati
      yesterday











    • @FabioTurati See Aconcagua's answer

      – NathanOliver
      yesterday






    • 6





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

      – Mehrdad
      19 hours ago














    32












    32








    32







    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 zx + 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 = [&]() 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 zx + 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 = [&]() 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 9 hours ago









    J.G.

    1259




    1259










    answered yesterday









    NathanOliverNathanOliver

    97.3k16138214




    97.3k16138214







    • 1





      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
      yesterday






    • 6





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

      – Mooing Duck
      yesterday











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

      – Fabio Turati
      yesterday











    • @FabioTurati See Aconcagua's answer

      – NathanOliver
      yesterday






    • 6





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

      – Mehrdad
      19 hours ago













    • 1





      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
      yesterday






    • 6





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

      – Mooing Duck
      yesterday











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

      – Fabio Turati
      yesterday











    • @FabioTurati See Aconcagua's answer

      – NathanOliver
      yesterday






    • 6





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

      – Mehrdad
      19 hours ago








    1




    1





    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
    yesterday





    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
    yesterday




    6




    6





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

    – Mooing Duck
    yesterday





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

    – Mooing Duck
    yesterday













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

    – Fabio Turati
    yesterday





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

    – Fabio Turati
    yesterday













    @FabioTurati See Aconcagua's answer

    – NathanOliver
    yesterday





    @FabioTurati See Aconcagua's answer

    – NathanOliver
    yesterday




    6




    6





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

    – Mehrdad
    19 hours ago






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

    – Mehrdad
    19 hours ago














    24














    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;





    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.

      – Nay Wunna Zaw
      11 hours ago






    • 2





      @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
      9 hours ago











    • @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.

      – Nay Wunna Zaw
      7 hours ago






    • 2





      @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
      6 hours ago
















    24














    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;





    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.

      – Nay Wunna Zaw
      11 hours ago






    • 2





      @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
      9 hours ago











    • @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.

      – Nay Wunna Zaw
      7 hours ago






    • 2





      @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
      6 hours ago














    24












    24








    24







    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;





    share|improve this 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;






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered yesterday









    AconcaguaAconcagua

    13.1k32145




    13.1k32145












    • 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.

      – Nay Wunna Zaw
      11 hours ago






    • 2





      @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
      9 hours ago











    • @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.

      – Nay Wunna Zaw
      7 hours ago






    • 2





      @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
      6 hours ago


















    • 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.

      – Nay Wunna Zaw
      11 hours ago






    • 2





      @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
      9 hours ago











    • @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.

      – Nay Wunna Zaw
      7 hours ago






    • 2





      @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
      6 hours ago

















    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.

    – Nay Wunna Zaw
    11 hours ago





    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.

    – Nay Wunna Zaw
    11 hours ago




    2




    2





    @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
    9 hours ago





    @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
    9 hours ago













    @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.

    – Nay Wunna Zaw
    7 hours ago





    @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.

    – Nay Wunna Zaw
    7 hours ago




    2




    2





    @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
    6 hours ago






    @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
    6 hours ago












    19














    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



























      19














      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

























        19












        19








        19







        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 yesterday









        Ted LyngmoTed Lyngmo

        3,5902522




        3,5902522





















            10














            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

























            • 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
              16 hours ago






            • 1





              @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
              13 hours ago















            10














            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

























            • 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
              16 hours ago






            • 1





              @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
              13 hours ago













            10












            10








            10







            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 13 hours ago

























            answered yesterday









            Toby SpeightToby Speight

            17.3k134368




            17.3k134368












            • 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
              16 hours ago






            • 1





              @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
              13 hours ago

















            • 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
              16 hours ago






            • 1





              @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
              13 hours ago
















            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
            16 hours ago





            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
            16 hours ago




            1




            1





            @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
            13 hours ago





            @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
            13 hours ago











            4














            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?

              – Nay Wunna Zaw
              12 hours ago











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

              – Peter Mortensen
              17 mins ago















            4














            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?

              – Nay Wunna Zaw
              12 hours ago











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

              – Peter Mortensen
              17 mins ago













            4












            4








            4







            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 9 hours ago









            ShadowRanger

            63.3k66099




            63.3k66099










            answered 19 hours ago









            ArteliusArtelius

            41.4k87895




            41.4k87895












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

              – Nay Wunna Zaw
              12 hours ago











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

              – Peter Mortensen
              17 mins ago

















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

              – Nay Wunna Zaw
              12 hours ago











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

              – Peter Mortensen
              17 mins ago
















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

            – Nay Wunna Zaw
            12 hours ago





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

            – Nay Wunna Zaw
            12 hours ago













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

            – Peter Mortensen
            17 mins ago





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

            – Peter Mortensen
            17 mins ago











            3














            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 zx + 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?

              – Nay Wunna Zaw
              yesterday











            • @NayWunnaZaw, yes, that is correct.

              – R Sahu
              yesterday






            • 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
              yesterday






            • 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
              yesterday















            3














            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 zx + 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?

              – Nay Wunna Zaw
              yesterday











            • @NayWunnaZaw, yes, that is correct.

              – R Sahu
              yesterday






            • 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
              yesterday






            • 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
              yesterday













            3












            3








            3







            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 zx + 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 zx + y;

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






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered yesterday









            R SahuR Sahu

            170k1294193




            170k1294193







            • 1





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

              – Nay Wunna Zaw
              yesterday











            • @NayWunnaZaw, yes, that is correct.

              – R Sahu
              yesterday






            • 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
              yesterday






            • 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
              yesterday












            • 1





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

              – Nay Wunna Zaw
              yesterday











            • @NayWunnaZaw, yes, that is correct.

              – R Sahu
              yesterday






            • 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
              yesterday






            • 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
              yesterday







            1




            1





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

            – Nay Wunna Zaw
            yesterday





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

            – Nay Wunna Zaw
            yesterday













            @NayWunnaZaw, yes, that is correct.

            – R Sahu
            yesterday





            @NayWunnaZaw, yes, that is correct.

            – R Sahu
            yesterday




            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
            yesterday





            @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
            yesterday




            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
            yesterday





            @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
            yesterday











            2














            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
              yesterday











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

              – Hiroki
              yesterday












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

              – Hiroki
              16 hours ago







            • 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
              16 hours ago











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

              – Hiroki
              5 hours ago















            2














            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
              yesterday











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

              – Hiroki
              yesterday












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

              – Hiroki
              16 hours ago







            • 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
              16 hours ago











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

              – Hiroki
              5 hours ago













            2












            2








            2







            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 16 hours ago

























            answered yesterday









            HirokiHiroki

            2,1353320




            2,1353320







            • 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
              yesterday











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

              – Hiroki
              yesterday












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

              – Hiroki
              16 hours ago







            • 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
              16 hours ago











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

              – Hiroki
              5 hours ago












            • 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
              yesterday











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

              – Hiroki
              yesterday












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

              – Hiroki
              16 hours ago







            • 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
              16 hours ago











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

              – Hiroki
              5 hours ago







            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
            yesterday





            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
            yesterday













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

            – Hiroki
            yesterday






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

            – Hiroki
            yesterday














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

            – Hiroki
            16 hours ago






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

            – Hiroki
            16 hours ago





            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
            16 hours ago





            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
            16 hours ago













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

            – Hiroki
            5 hours ago





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

            – Hiroki
            5 hours ago











            1














            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++?

              – Nay Wunna Zaw
              7 hours ago






            • 1





              @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
              7 hours ago











            • 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.

              – Nay Wunna Zaw
              6 hours ago















            1














            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++?

              – Nay Wunna Zaw
              7 hours ago






            • 1





              @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
              7 hours ago











            • 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.

              – Nay Wunna Zaw
              6 hours ago













            1












            1








            1







            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 8 hours ago









            Jonathan MeeJonathan Mee

            22k1066176




            22k1066176












            • 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++?

              – Nay Wunna Zaw
              7 hours ago






            • 1





              @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
              7 hours ago











            • 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.

              – Nay Wunna Zaw
              6 hours ago

















            • 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++?

              – Nay Wunna Zaw
              7 hours ago






            • 1





              @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
              7 hours ago











            • 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.

              – Nay Wunna Zaw
              6 hours ago
















            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++?

            – Nay Wunna Zaw
            7 hours ago





            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++?

            – Nay Wunna Zaw
            7 hours ago




            1




            1





            @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
            7 hours ago





            @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
            7 hours ago













            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.

            – Nay Wunna Zaw
            6 hours ago





            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.

            – Nay Wunna Zaw
            6 hours ago











            0














            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























            • 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
              18 hours ago
















            0














            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























            • 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
              18 hours ago














            0












            0








            0







            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 23 hours ago









            o11co11c

            10.9k43154




            10.9k43154












            • 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
              18 hours ago


















            • 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
              18 hours ago

















            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
            18 hours ago






            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
            18 hours ago











            Nay Wunna Zaw is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            Nay Wunna Zaw is a new contributor. Be nice, and check out our Code of Conduct.












            Nay Wunna Zaw is a new contributor. Be nice, and check out our Code of Conduct.











            Nay Wunna Zaw is a new contributor. Be nice, and check out our Code of Conduct.














            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-do-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

            Is it wise to focus on putting odd beats on left when playing double bass drums?What does the tie across other different notes mean?How to improve right hand picking/strumming technique for electric and acoustic guitar?How fast is the BPM should you start to use double bass pedal?Alternative or more advanced methods for counting rhythmsLost direction in practicing drumsIs there any way at all to tell if these measures are 6/4 vs. 3/2?Why is alberti bass so tiring?How does 'meter' differ from 'rhythm' in music?Rhythm question about piano sheet notationWhy is Bach's Cello Suite 1 written in 16th notes

            map list to bin numbersquantilization (if that is a word)Map efficiently over duplicates in listGenerating a list of cubefree numbersIs there an equivalent to MATLAB's linspace?Convert a list of hexadecimal numbers to decimalTaking one list Mod a second listlist of items and group of alternative itemsHow find numbers in this list of inequalities?Selecting list entries with a True False index list of similar lengthReplace element in array by checking condition in another listAttempting to fill a table with the number of elements in each bin and make a table with the elements in the bins?

            History of India Contents Prehistoric era (until c. 3300 BCE) Bronze Age – "First urbanisation" (c. 3300 – c. 1800 BCE) Climate change, de-urbanisation, and Indo-Aryan migrations (c.1800 – 1500 BCE) Iron Age - Vedic period (c. 1500 – c. 600 BCE) "Second urbanisation" (c. 600 – c. 200 BCE) Classical to early medieval periods (c. 200 BCE – c. 1200 CE) Late medieval period (c. 1200 – 1526 CE) Early modern period (c. 1526–1858 CE) Modern period and independence (after c. 1850 CE) Historiography See also References Further reading External links Navigation menureviewedee[update]The crisisThe Evolution and History of Human Populations in South Asia: Inter-disciplinary Studies in Archaeology, Biological Anthropology, Linguistics and GeneticsThe Ancient Indus: Urbanism, Economy, and Society"Indus River Valley Civilizations"The Ancient Indus: Urbanism, Economy, and Society"India before the British: The Mughal Empire and its Rivals, 1526–1857"Why Europe Grew Rich and Asia Did Not: Global Economic Divergence, 1600–1850Development Centre Studies The World Economy Historical Statistics: Historical StatisticsDeveloping cultures: case studiesEthnic Groups of South Asia and the Pacific: An Encyclopedia: An Encyclopedia"Indian Economy During British Rule""Economic Impact of the British Rule in India | Indian History"The Bone Readers: Science and Politics in Human Origins Research"Out of Africa: new hypotheses and evidence for the dispersal of Homo sapiens along the Indian Ocean rim"10.3109/0301446100363924920334598"Genetic and archaeological perspectives on the initial modern human colonization of southern Asia"2013PNAS..11010699M10.1073/pnas.1306043110369678523754394"Edakkal Caves|Places Around in Wayanad"Protecting megaliths to keep history alive The Hindu daily"Archaeologists rock solid behind Edakkal Cave"The Global Prehistory of Human Migration"Indus Valley 2,000 years older than thought"the original"Stepwells -Cosmology of Subterranean Architecture as seen in Adalaj"A History of Ancient and Early medieval India : from the Stone Age to the 12th century"Stone celts in Harappa"the original"Peoples and languages in pre-islamic Indus valley"the original"The Sindhi language"the originalThe Aryan chromosome"Fluvial landscapes of the Harappan Civilization"2012PNAS..109E1688G10.1073/pnas.1112743109338705422645375"Is River Ghaggar, Saraswati? Geochemical Constraints""An Ancient Civilization, Upended by Climate Change""Huge Ancient Civilization's Collapse Explained"2003GeoRL..30.1425S10.1029/2002GL0168222006QSRv...25.1283M10.1016/j.quascirev.2005.10.0122011QuInt.229..140M10.1016/j.quaint.2009.11.012Climate Change and the Course of Global History: A Rough JourneyA History of Ancient and Early Medieval India: From the Stone Age to the 12th CenturyA History of Ancient and Mediaeval India: From the Stone Age to the 12th CenturyAntennae SwordA History of IndiaA History of IndiaAn Introduction to Hinduism"India: The Late 2nd Millennium and the Reemergence of Urbanism"The Coinage of Ancient IndiaA Sanskrit reader: with vocabulary and notesPedigree: the origins of words from nature"Early Sanskritization. Origins and Development of the Kuru State"10.11588/ejvs.1995.4.823The Sanskrit epics, Part 2The City in South AsiaThe UpanishadsAn Introduction to HinduismReligions of the World, Second Edition: A Comprehensive Encyclopedia of Beliefs and PracticesA History of Ancient and Early Medieval India: From the Stone Age to the 12th CenturyEarly India: From the Origins to AD 1300Republics in ancient Indiapp. 83ff"Magadha Empire""Lumbini Development Trust: Restoring the Lumbini Garden"the originalThe great armies of antiquityarchived"The Achaemenid Persian Empire (550–330 B.C.)""East–West Orientation of Historical Empires"1076-156X"Dinner on the Grand Trunk Road"10.2307/32502263250226"Silappathikaram Tamil Literature"the originalManimekalai – English transliteration of Tamil originalIndian Temple Architecture: Form and Transformation : the Karṇāṭa Drāviḍa Tradition, 7th to 13th CenturiesBuddhist ArchitectureA History of India"The World Economy (GDP) : Historical Statistics by Professor Angus Maddison"The World Economy – Volume 1: A Millennial Perspective and Volume 2: Historical Statistics10.2307/32502140004-36483250214A Comprehensive History of India: Volume 2Between the Empires: Society in India, 300 to 400Emergence of Viṣṇu and Śiva Images in India: Numismatic and Sculptural Evidence"Parthian Pair of Earrings"the originalThe Medical Times and Gazette, Volume 1Greatest emporium in the worldThe Cambridge History of Ancient China: From the Origins of Civilization to 221 BCBuddhist Records of the Western WorldArchaeology in Soviet Central AsiaThe Grandeur of Gandhara: The Ancient Buddhist Civilization of the Swat, Peshawar, Kabul and Indus ValleysIndian Sculpture: Circa 500 B.C.-A.D. 700"The History of Pakistan: The Kushans"Gupta Dynasty – MSN Encartathe original"India – Historical Setting – The Classical Age – Gupta and Harsha""Gupta Dynasty, Golden Age Of India"the original"The Age of the Guptas and After"the originalNumber Theory and Its History"Gupta dynasty (Indian dynasty)""Gupta dynasty: empire in 4th century"the original"The Story of India – Photo Gallery"The ASI say499315420"Pallava script"p. 145"CNG: eAuction 329. INDIA, Post-Gupta (Ganges Valley). Vardhanas of Thanesar and Kanauj. Harshavardhana. Circa AD 606–647. AR Drachm (13mm, 2.28 g, 1h)""Harsha""Sthanvishvara (historical region, India)""Harsha (Indian emperor)"Shyama Kumar Chattopadhyaya (2000) The Philosophy of Sankar's Advaita VedantaShankara's IntroductionShankara's Introduction19373677Shankara's IntroductionIs The Buddhist 'No-Self' Doctrine Compatible With Pursuing Nirvana?The Seven Spiritual Laws Of YogaIndia: The Ancient Past. A History of the Indian-Subcontinent from 7000 BC to AD 1200The Kashmir Series: Glimpses of Kashmiri Culture – Vivekananda Kendra, Kanyakumari (p. 57).Al-Hind: Early Medieval India and the Expansion of Islam, 7th–11th CenturiesHistory of GopāchalaLand of Two Rivers: A History of Bengal from the Mahabharata to MujibEuropean Trade and Colonial ConquestA History of IndiaA Comprehensive History Of Ancient India (3 Vol. Set)"The Last Years of Cholas: The decline and fall of a dynasty"the originalFascinating Hindutva: Saffron Politics and Dalit MobilisationGazetteer of the province of OudhAl- Hind: The slave kings and the Islamic conquest. 2"Shahi Family"The Cambridge history of Islam"Ameer Nasir-ood-deen Subooktugeen"Gazetteer of the Attock District, 1930, Part 1Land of seven rivers: History of India's GeographyTemple Desecration and Indo-Muslim StatesIslam in South Asia: A Short HistoryBeyond Orientalism: The Work of Wilhelm Halbfass and Its Impact on Indian and Cross-cultural StudiesThe Making of Terrorism in Pakistan: Historical and Social Roots of ExtremismOrnament in Indian ArchitectureA historical review of Hindu India: 300 B.C. to 1200 A.D."Indian States and Union Territories"Islam in South Asia: A Short HistoryA Brief History of the Indian PeoplesThe Modern ReviewDelhi Sultanate"Battuta's Travels: Delhi, capital of Muslim India"the original"Timur – conquest of India"the originalIndia HandbookBhaktiThe Four Denomination of Hinduism10.1007/s11407-008-9049-925691067"Vijayanagara Research Project::Elephant Stables"10.2307/26465262646526Historical Dictionary of the TamilsBihar General Knowledge DigestMapping Bihar: From Medieval to Modern TimesPopular Literature and Pre-modern Societies in South AsiaA manual of the Kistna district in the presidency of MadrasAncient Indian History and CivilizationFragmented Memories: Struggling to be Tai-Ahom in India"The Islamic World to 1600: Rise of the Great Islamic Empires (The Mughal Empire)"the originalDynasties: A Global History of Power, 1300–1800, p. 105"Whose fort is it anyway"10.1111/0020-8833.000532600793Development Centre Studies The World Economy Historical Statistics: Historical Statistics"India's Deindustrialization in the 18th and 19th Centuries"The Mughal Empire, p. 190"The Long Globalization and Textile Producers in India"The Mughal World: Life in India's Last Golden AgeAurangzeb: The Life and Legacy of India's Most Controversial KingIn the Shadow of the Taj: A Portrait of Agra"Iran in the Age of the Raj"p. 8610.2307/20539802053980Delhi, the Capital of IndiaAn Advanced History of Modern India"Journal of the Tanjore Maharaja Serfoji's Sarasvati Mahal Library"The Rediscovery of India: A New SubcontinentIslamic Renaissance In South Asia (1707–1867) : The Role Of Shah Waliallah & His SuccessorsAn Advanced History of Modern IndiaThe Great Maratha Mahadaji Scindia"Full text of "Selections from the papers of Lord Metcalfe; late governor-general of India, governor of Jamaica, and governor-general of Canada""The Discovery Of IndiaThe Sacred City of the Hindus: An Account of Benares in Ancient and Modern TimesResurrecting Banaras: Urban Space, Architecture and Religious BoundariesFaith & Philosophy of Sikhism"Missiles mainstay of Pak's N-arsenal"History Modern India By S.N. Sen"Sirajuddaula"ArchivedLongman History & Civics (Dual Government in Bengal)Madhya Pradesh National Means-Cum-Merit Scholarship Exam (Warren Hasting's system of Dual Government)A Military History of Britain: from 1775 to the PresentIndian Cultural Heritage Perspective For TourismHindu Rulers, Muslim Subjects: Islam, Rights, and the History of KashmirIndian HistoryAn Atlas and Survey of South Asian HistoryAn Historical Account of the British Trade Over the Caspian SeaIndian Merchants and Eurasian Trade, 1600–1750The Indian diaspora in Central Asia and its trade, 1550–1900From Constantinople to the home of Omar Khayyam: travels in Transcaucasia and northern Persia for historic and literary researchA journey from Bengal to England: through the northern part of India, Kashmire, Afghanistan, and Persia, and into Russia, by the Caspian-SeaA Second Journey through Persia, Armenia, and Asia Minor, to Constantinople, between the Years 1810 and 1816Reports from the consuls of the United States, 1887Portugal and its Empire, 1250–1800 (Collected Essays in Memory of Glenn J. Ames).: Portuguese Studies Review, Vol. 17, No. 1The Dutch Power in Kerala, 1729–1758http://mod.nic.inArchivedDossier Goa – A Recusa do Sacrifício InútilAn Imperial Crisis in British India: The Manipur Uprising of 1891The Truth of Babri Mosque"Kolkata (Calcutta) : History"the original"Robert Clive, Baron Clive, 'Clive of India', 1725–1774""The Transformation from a Pre-Colonial to a Colonial Order: The Case of India"10.2307/25955872595587A versatile geniusArchived10.1109/MWSYM.1997.602854"Rabindranath Tagore on Education"the original"Essay on 'Derozio and the Young Bengal Movement'"Poverty and Famines: An Essay on Entitlement and Deprivation"Plague"the originalPopulation Growth and Land Use"Reintegrating India with the World Economy""Census Of India 1931"A history of modern India, 1480–1950"'India's well-timed diversification of army helped democracy' | Business Standard News"Bal Gangadhar Tilak: Struggle for Swaraj"Participants from the Indian subcontinent in the First World War""Commonwealth War Graves Commission Annual Report 2007–2008 Online"the original1462689197110.1017/s0010417500016534178920Eurocentrism: a marxian critical realist critique"Ranjit Guha, "On Some Aspects of Historiography of Colonial India""10.2307/2168385216838510.7202/016593ar"Harvard scholar says the idea of India dates to a much earlier time than the British or the Mughals""In The Footsteps of Pilgrims""India's spiritual landscape: The heavens and the earth""India: A Sacred Geography by Diana L Eck – review"Modern India: The Origins of an Asian Democracy10.2307/21694222169422964322464"The Indian Subcontinent and 'Out of Africa 1'"254043308Encyclopedia of World ReligionsThe Evolution and History of Human Populations in South Asia: Inter-disciplinary Studies in Archaeology, Biological Anthropology, Linguistics and Genetics"The Early Paleolithic of the Indian Subcontinent: Hominin Colonization, Dispersals and Occupation History"Ancient Indian History and CivilizationAncient Indian Social History: Some Interpretationsthe originalIndia Before EuropeA Concise History of Modern India"The beginning of the historical period, c. 500–150 BCE"full textA History of Indiathe originalexcerpt and text searchexcerptexcerptAn Economic History of India: From Pre-Colonial Times to 1991excerpt and text searchexcerpt and text searchIndia as known to the ancient world10.1111/j.1468-0289.1985.tb00391.x2597191onlineThe History of India, as told by its own historians. The Muhammadan Periodonline editionHans William Brown research collection on 19th-century missionary work in India, 1882–1932, Ms. Coll. 1033, Kislak Center for Special Collections, Rare Books and Manuscripts, University of Pennsylvaniaee