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?Image 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++ostream and istream overlaloading without << / >> operatorDeoptimizing a program for the pipeline in Intel Sandybridge-family CPUsSetting two variables *always* equal?

Solution of this Diophantine Equation

Why do remote companies require working in the US?

Why is there a PLL in CPU?

declare as function pointer and initialize in the same line

How can I get through very long and very dry, but also very useful technical documents when learning a new tool?

Describing a person. What needs to be mentioned?

Inappropriate reference requests from Journal reviewers

If the heap is initialized for security, then why is the stack uninitialized?

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

When did Lisp start using symbols for arithmetic?

suction cup thing with 1/4 TRS cable?

What is the meaning of "rider"?

I believe this to be a fraud

Grabbing quick drinks

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

What is the difference between "behavior" and "behaviour"?

Any way to transfer all permissions from one role to another?

What makes a siege story/plot interesting?

The King's new dress

Why did we only see the N-1 starfighters in one film?

Why does standard notation not preserve intervals (visually)

Why didn't Theresa May consult with Parliament before negotiating a deal with the EU?

What happens if you roll doubles 3 times then land on "Go to jail?"

Are there languages with no euphemisms?



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?Image 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++ostream and istream overlaloading without << / >> operatorDeoptimizing a program for the pipeline in Intel Sandybridge-family CPUsSetting two variables *always* equal?










11















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.




















  • Why do you want to do that?

    – Robert Andrzejuk
    2 hours ago











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

    – Pete Becker
    2 hours ago






  • 1





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






  • 2





    @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
    1 hour ago















11















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.




















  • Why do you want to do that?

    – Robert Andrzejuk
    2 hours ago











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

    – Pete Becker
    2 hours ago






  • 1





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






  • 2





    @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
    1 hour ago













11












11








11


2






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






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







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









Nay Wunna ZawNay Wunna Zaw

586




586




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.












  • Why do you want to do that?

    – Robert Andrzejuk
    2 hours ago











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

    – Pete Becker
    2 hours ago






  • 1





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






  • 2





    @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
    1 hour ago

















  • Why do you want to do that?

    – Robert Andrzejuk
    2 hours ago











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

    – Pete Becker
    2 hours ago






  • 1





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






  • 2





    @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
    1 hour ago
















Why do you want to do that?

– Robert Andrzejuk
2 hours ago





Why do you want to do that?

– Robert Andrzejuk
2 hours ago













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

– Pete Becker
2 hours ago





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

– Pete Becker
2 hours ago




1




1





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




2




2





@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
1 hour 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
1 hour ago












5 Answers
5






active

oldest

votes


















4














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 chnage 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;
reutrn cache_result;

;





share|improve this answer




















  • 2





    Shouldn't the caches have a type?

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


















13














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






























    5














    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














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











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

        – Hiroki
        3 hours ago












      • Why downvoted ?? At least I posted my answer faster than the selected one with my test code. Hmm...

        – Hiroki
        37 mins ago


















      1














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











      • @NayWunnaZaw, yes, that is correct.

        – R Sahu
        3 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
        3 hours ago






      • 2





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

      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4














      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 chnage 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;
      reutrn cache_result;

      ;





      share|improve this answer




















      • 2





        Shouldn't the caches have a type?

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















      4














      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 chnage 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;
      reutrn cache_result;

      ;





      share|improve this answer




















      • 2





        Shouldn't the caches have a type?

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













      4












      4








      4







      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 chnage 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;
      reutrn 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 chnage 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;
      reutrn cache_result;

      ;






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 2 hours ago

























      answered 3 hours ago









      NathanOliverNathanOliver

      97.1k16137212




      97.1k16137212







      • 2





        Shouldn't the caches have a type?

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












      • 2





        Shouldn't the caches have a type?

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







      2




      2





      Shouldn't the caches have a type?

      – Aconcagua
      3 hours ago





      Shouldn't the caches have a type?

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













      13














      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



























        13














        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

























          13












          13








          13







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









          Ted LyngmoTed Lyngmo

          3,5602522




          3,5602522





















              5














              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



























                5














                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

























                  5












                  5








                  5







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









                  AconcaguaAconcagua

                  12.9k32144




                  12.9k32144





















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











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

                        – Hiroki
                        3 hours ago












                      • Why downvoted ?? At least I posted my answer faster than the selected one with my test code. Hmm...

                        – Hiroki
                        37 mins 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
                        3 hours ago











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

                        – Hiroki
                        3 hours ago












                      • Why downvoted ?? At least I posted my answer faster than the selected one with my test code. Hmm...

                        – Hiroki
                        37 mins 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 3 hours ago

























                      answered 3 hours ago









                      HirokiHiroki

                      2,1163320




                      2,1163320







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











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

                        – Hiroki
                        3 hours ago












                      • Why downvoted ?? At least I posted my answer faster than the selected one with my test code. Hmm...

                        – Hiroki
                        37 mins 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
                        3 hours ago











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

                        – Hiroki
                        3 hours ago












                      • Why downvoted ?? At least I posted my answer faster than the selected one with my test code. Hmm...

                        – Hiroki
                        37 mins 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
                      3 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
                      3 hours ago













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

                      – Hiroki
                      3 hours ago






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

                      – Hiroki
                      3 hours ago














                      Why downvoted ?? At least I posted my answer faster than the selected one with my test code. Hmm...

                      – Hiroki
                      37 mins ago





                      Why downvoted ?? At least I posted my answer faster than the selected one with my test code. Hmm...

                      – Hiroki
                      37 mins ago











                      1














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











                      • @NayWunnaZaw, yes, that is correct.

                        – R Sahu
                        3 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
                        3 hours ago






                      • 2





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















                      1














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











                      • @NayWunnaZaw, yes, that is correct.

                        – R Sahu
                        3 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
                        3 hours ago






                      • 2





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













                      1












                      1








                      1







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











                      • @NayWunnaZaw, yes, that is correct.

                        – R Sahu
                        3 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
                        3 hours ago






                      • 2





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











                      • @NayWunnaZaw, yes, that is correct.

                        – R Sahu
                        3 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
                        3 hours ago






                      • 2





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













                      @NayWunnaZaw, yes, that is correct.

                      – R Sahu
                      3 hours ago





                      @NayWunnaZaw, yes, that is correct.

                      – R Sahu
                      3 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
                      3 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
                      3 hours ago




                      2




                      2





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

                      Ружовы пелікан Змест Знешні выгляд | Пашырэнне | Асаблівасці біялогіі | Літаратура | НавігацыяДагледжаная версіяправерана1 зменаДагледжаная версіяправерана1 змена/ 22697590 Сістэматыкана ВіківідахВыявына Вікісховішчы174693363011049382

                      ValueError: Error when checking input: expected conv2d_13_input to have shape (3, 150, 150) but got array with shape (150, 150, 3)2019 Community Moderator ElectionError when checking : expected dense_1_input to have shape (None, 5) but got array with shape (200, 1)Error 'Expected 2D array, got 1D array instead:'ValueError: Error when checking input: expected lstm_41_input to have 3 dimensions, but got array with shape (40000,100)ValueError: Error when checking target: expected dense_1 to have shape (7,) but got array with shape (1,)ValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (0,)Keras exception: ValueError: Error when checking input: expected conv2d_1_input to have shape (150, 150, 3) but got array with shape (256, 256, 3)Steps taking too long to completewhen checking input: expected dense_1_input to have shape (13328,) but got array with shape (317,)ValueError: Error when checking target: expected dense_3 to have shape (None, 1) but got array with shape (7715, 40000)Keras exception: Error when checking input: expected dense_input to have shape (2,) but got array with shape (1,)

                      Illegal assignment from SObject to ContactFetching String, Id from Map - Illegal Assignment Id to Field / ObjectError: Compile Error: Illegal assignment from String to BooleanError: List has no rows for assignment to SObjectError on Test Class - System.QueryException: List has no rows for assignment to SObjectRemote action problemDML requires SObject or SObject list type error“Illegal assignment from List to List”Test Class Fail: Batch Class: System.QueryException: List has no rows for assignment to SObjectMapping to a user'List has no rows for assignment to SObject' Mystery