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

前端 未结 12 1760
傲寒
傲寒 2021-02-02 05:34

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

12条回答
  •  南方客
    南方客 (楼主)
    2021-02-02 05:50

    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.

提交回复
热议问题