Home > Mobile >  How can I set a c variable to permanently be the sum of two others?
How can I set a c variable to permanently be the sum of two others?

Time:07-17

I want to permanently set one variable to be the sum of two other integer variables in c , such that the value of the sum variable will change as either or both of the original two variables change:

#include <iostream>

int main() 
{
    int myInt = 3;
    int myInt2 = 5;

    int mySum = myInt   myInt2; // Something here so that mySum changes with myInt and myInt2

    std::cout << mySum << std::endl; // Should output 8

    myInt = 10;

    std::cout << mySum << std::endl; // Should output 15

    myInt2 = 30;

    std::cout << mySum; // Should output 40
}

Is this possible to do, whether with references/pointers or some other method?

CodePudding user response:

This isn't what you asked for (which can't be done in C ) but it has a similar effect. Maybe you'll find it acceptable

#include <iostream>

struct IntPair
{
    int sum() const { return x   y; }
    int x, y;
};

int main() 
{
    IntPair p{ 3, 5 };

    std::cout << p.sum() << std::endl; // Should output 8

    p.x = 10;

    std::cout << p.sum() << std::endl; // Should output 15

    p.y = 30;

    std::cout << p.sum(); // Should output 40
}

CodePudding user response:

You cannot achieve this with the exact same syntax you're suggesting, but you can create a type containing 2 references to int that behaves reasonably similar to an int resulting in the desired behaviour:

class Sum
{
public:
    Sum(const int& s1, const int& s2) noexcept
        : m_s1(s1), m_s2(s2)
    {}

    operator int() const noexcept
    {
        return m_s1   m_s2;
    }

private:
    const int& m_s1;
    const int& m_s2;
};

std::ostream& operator<<(std::ostream& s, Sum const& sum)
{
    s << static_cast<int>(sum);
    return s;
}

int main()
{
    int myInt = 3;
    int myInt2 = 5;

    Sum mySum(myInt, myInt2);

    std::cout << mySum << std::endl; // outputs 8

    myInt = 10;

    std::cout << mySum << std::endl; // outputs 15

    myInt2 = 30;

    std::cout << mySum << std::endl; // outputs 40

    std::cout << (mySum   1) << std::endl; // outputs 41
}
  • Related