How to make a variable always equal to the result of some calculations? The Next CEO of Stack OverflowHow to detect unsigned integer multiply overflow?The Definitive C++ Book Guide and ListIs the sizeof(some pointer) always equal to four?Using scanf() in C++ programs is faster than using cin?Pretty-print C++ STL containersImage Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionReplacing a 32-bit loop counter with 64-bit introduces crazy performance deviationsCreate istream and ostream objects in C++Deoptimizing a program for the pipeline in Intel Sandybridge-family CPUsSetting two variables *always* equal?

When Does an Atlas Uniquely Define a Manifold?

Can I equip Skullclamp on a creature I am sacrificing?

What is the point of a new vote on May's deal when the indicative votes suggest she will not win?

If I blow insulation everywhere in my attic except the door trap, will heat escape through it?

Return the Closest Prime Number

How do we know the LHC results are robust?

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

Implement the Thanos sorting algorithm

How do I go from 300 unfinished/half written blog posts, to published posts?

Does the Brexit deal have to be agreed by both Houses?

Describing a person. What needs to be mentioned?

Where to find order of arguments for default functions

What's the point of interval inversion?

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

How did people program for Consoles with multiple CPUs?

How to safely derail a train during transit?

Why do remote companies require working in the US?

Trouble understanding the speech of overseas colleagues

Rotate a column

Anatomically Correct Strange Women In Ponds Distributing Swords

Whats the best way to handle refactoring a big file?

Only print output after finding pattern

How to write papers efficiently when English isn't my first language?

What does this shorthand mean?



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



The Next CEO of Stack OverflowHow to detect unsigned integer multiply overflow?The Definitive C++ Book Guide and ListIs the sizeof(some pointer) always equal to four?Using scanf() in C++ programs is faster than using cin?Pretty-print C++ STL containersImage Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionReplacing a 32-bit loop counter with 64-bit introduces crazy performance deviationsCreate istream and ostream objects in C++Deoptimizing a program for the pipeline in Intel Sandybridge-family CPUsSetting two variables *always* equal?










17















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;









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.















  • 1





    Why do you want to do that?

    – Robert Andrzejuk
    12 hours ago






  • 1





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

    – Pete Becker
    12 hours ago






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






  • 5





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






  • 3





    That's called a "function."

    – ApproachingDarknessFish
    6 hours ago















17















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;









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.















  • 1





    Why do you want to do that?

    – Robert Andrzejuk
    12 hours ago






  • 1





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

    – Pete Becker
    12 hours ago






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






  • 5





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






  • 3





    That's called a "function."

    – ApproachingDarknessFish
    6 hours ago













17












17








17


5






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;









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;






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







Nay Wunna Zaw













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









Nay Wunna ZawNay Wunna Zaw

8810




8810




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.







  • 1





    Why do you want to do that?

    – Robert Andrzejuk
    12 hours ago






  • 1





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

    – Pete Becker
    12 hours ago






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






  • 5





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






  • 3





    That's called a "function."

    – ApproachingDarknessFish
    6 hours ago












  • 1





    Why do you want to do that?

    – Robert Andrzejuk
    12 hours ago






  • 1





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

    – Pete Becker
    12 hours ago






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






  • 5





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






  • 3





    That's called a "function."

    – ApproachingDarknessFish
    6 hours ago







1




1





Why do you want to do that?

– Robert Andrzejuk
12 hours ago





Why do you want to do that?

– Robert Andrzejuk
12 hours ago




1




1





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

– Pete Becker
12 hours ago





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

– Pete Becker
12 hours ago




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





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




5




5





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





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




3




3





That's called a "function."

– ApproachingDarknessFish
6 hours ago





That's called a "function."

– ApproachingDarknessFish
6 hours ago












7 Answers
7






active

oldest

votes


















12














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 = [&]() static auto cache_x = x; 
static auto cache_y = y;
static auto cache_result = x + y;
if (x == cache_x && y == cache_y)
return cache_result;
else

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

;





share|improve this answer




















  • 2





    Shouldn't the caches have a type?

    – Aconcagua
    12 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
    12 hours ago











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

    – Mooing Duck
    7 hours ago











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

    – Fabio Turati
    6 hours ago











  • @FabioTurati See Aconcagua's answer

    – NathanOliver
    5 hours ago


















18














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






























    8














    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






























      2














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











      • @NayWunnaZaw, yes, that is correct.

        – R Sahu
        12 hours ago






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






      • 3





        @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
        12 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 x;
      int y;
      const auto z = [&x, &y]() return x+y; ;





      share|improve this answer




















      • 1





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











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

        – Hiroki
        12 hours ago












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

        – Hiroki
        5 hours ago


















      2














      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.


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


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






      share|improve this answer






























        -1














        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























          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-to-make-a-variable-always-equal-to-the-result-of-some-calculations%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          12














          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 = [&]() static auto cache_x = x; 
          static auto cache_y = y;
          static auto cache_result = x + y;
          if (x == cache_x && y == cache_y)
          return cache_result;
          else

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

          ;





          share|improve this answer




















          • 2





            Shouldn't the caches have a type?

            – Aconcagua
            12 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
            12 hours ago











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

            – Mooing Duck
            7 hours ago











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

            – Fabio Turati
            6 hours ago











          • @FabioTurati See Aconcagua's answer

            – NathanOliver
            5 hours ago















          12














          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 = [&]() static auto cache_x = x; 
          static auto cache_y = y;
          static auto cache_result = x + y;
          if (x == cache_x && y == cache_y)
          return cache_result;
          else

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

          ;





          share|improve this answer




















          • 2





            Shouldn't the caches have a type?

            – Aconcagua
            12 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
            12 hours ago











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

            – Mooing Duck
            7 hours ago











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

            – Fabio Turati
            6 hours ago











          • @FabioTurati See Aconcagua's answer

            – NathanOliver
            5 hours ago













          12












          12








          12







          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 = [&]() static auto cache_x = x; 
          static auto cache_y = y;
          static auto cache_result = x + y;
          if (x == cache_x && y == cache_y)
          return cache_result;
          else

          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 = [&]() static auto cache_x = x; 
          static auto cache_y = y;
          static auto cache_result = x + y;
          if (x == cache_x && y == cache_y)
          return cache_result;
          else

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









          isanae

          2,53711437




          2,53711437










          answered 12 hours ago









          NathanOliverNathanOliver

          97.1k16137214




          97.1k16137214







          • 2





            Shouldn't the caches have a type?

            – Aconcagua
            12 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
            12 hours ago











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

            – Mooing Duck
            7 hours ago











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

            – Fabio Turati
            6 hours ago











          • @FabioTurati See Aconcagua's answer

            – NathanOliver
            5 hours ago












          • 2





            Shouldn't the caches have a type?

            – Aconcagua
            12 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
            12 hours ago











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

            – Mooing Duck
            7 hours ago











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

            – Fabio Turati
            6 hours ago











          • @FabioTurati See Aconcagua's answer

            – NathanOliver
            5 hours ago







          2




          2





          Shouldn't the caches have a type?

          – Aconcagua
          12 hours ago





          Shouldn't the caches have a type?

          – Aconcagua
          12 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
          12 hours ago





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













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

          – Mooing Duck
          7 hours ago





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

          – Mooing Duck
          7 hours ago













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

          – Fabio Turati
          6 hours ago





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

          – Fabio Turati
          6 hours ago













          @FabioTurati See Aconcagua's answer

          – NathanOliver
          5 hours ago





          @FabioTurati See Aconcagua's answer

          – NathanOliver
          5 hours ago













          18














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



          #include <iostream>

          int main()
          int x;
          int y;

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

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







          share|improve this answer



























            18














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



            #include <iostream>

            int main()
            int x;
            int y;

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

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







            share|improve this answer

























              18












              18








              18







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









              Ted LyngmoTed Lyngmo

              3,5802522




              3,5802522





















                  8














                  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



























                    8














                    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

























                      8












                      8








                      8







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









                      AconcaguaAconcagua

                      12.9k32144




                      12.9k32144





















                          2














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











                          • @NayWunnaZaw, yes, that is correct.

                            – R Sahu
                            12 hours ago






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






                          • 3





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















                          2














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











                          • @NayWunnaZaw, yes, that is correct.

                            – R Sahu
                            12 hours ago






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






                          • 3





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













                          2












                          2








                          2







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









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











                          • @NayWunnaZaw, yes, that is correct.

                            – R Sahu
                            12 hours ago






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






                          • 3





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












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











                          • @NayWunnaZaw, yes, that is correct.

                            – R Sahu
                            12 hours ago






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






                          • 3





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







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





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













                          @NayWunnaZaw, yes, that is correct.

                          – R Sahu
                          12 hours ago





                          @NayWunnaZaw, yes, that is correct.

                          – R Sahu
                          12 hours ago




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





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




                          3




                          3





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





                          @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
                          12 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 x;
                          int y;
                          const auto z = [&x, &y]() return x+y; ;





                          share|improve this answer




















                          • 1





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











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

                            – Hiroki
                            12 hours ago












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

                            – 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 x;
                          int y;
                          const auto z = [&x, &y]() return x+y; ;





                          share|improve this answer




















                          • 1





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











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

                            – Hiroki
                            12 hours ago












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

                            – 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 x;
                          int y;
                          const auto z = [&x, &y]() return x+y; ;





                          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 x;
                          int y;
                          const auto z = [&x, &y]() return x+y; ;






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited 12 hours ago

























                          answered 12 hours ago









                          HirokiHiroki

                          2,1253320




                          2,1253320







                          • 1





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











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

                            – Hiroki
                            12 hours ago












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

                            – Hiroki
                            5 hours ago












                          • 1





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











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

                            – Hiroki
                            12 hours ago












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

                            – Hiroki
                            5 hours ago







                          1




                          1





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





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













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

                          – Hiroki
                          12 hours ago






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

                          – Hiroki
                          12 hours ago














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

                          – Hiroki
                          5 hours ago





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

                          – Hiroki
                          5 hours ago











                          2














                          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.


                          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



























                            2














                            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.


                            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

























                              2












                              2








                              2







                              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.


                              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.


                              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










                              answered 9 hours ago









                              Toby SpeightToby Speight

                              17.2k134367




                              17.2k134367





















                                  -1














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




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



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



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






                                  share|improve this answer



























                                    -1














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




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



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



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






                                    share|improve this answer

























                                      -1












                                      -1








                                      -1







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









                                      o11co11c

                                      10.9k43154




                                      10.9k43154




















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

                                          Wikipedia:Contact us Navigation menu Navigation menuLeave a Reply Cancel reply Post navigationRecent PostsRecent CommentsArchivesCategoriesMeta

                                          Farafra Inhaltsverzeichnis Geschichte | Badr-Museum Farafra | Nationalpark Weiße Wüste (as-Sahra al-baida) | Literatur | Weblinks | Navigationsmenü27° 3′ N, 27° 58′ OCommons: Farafra

                                          Tórshavn Kliima | Partnerstääden | Luke uk diar | Nawigatsjuun62° 1′ N, 6° 46′ W62° 1′ 0″ N, 6° 46′ 0″ WWMOTórshavn