cfreestandinggnu99

If something is a const volatile int, can it change based on the status of a variable?


I have a unsigned const volatile short int*. I want it to be (x + y), which at time of defining is set to 0. However, i want if for some reason y changes to 5, i would want the unsigned const volatile short int* to change too.

Would this be possible in C?

(Note: I am using freestanding C99 mode with GNU extensions, and i mean for it to change automatically and not with a function.)


Solution

  • There is no way to make variables automatically update based on other variables like that in C.

    Instead of storing the sum of x and y in a variable, you should consider just making a function that recomputes the sum whenever you need it. The addition should be pretty fast:

    int get_the_sum()
    {
        return x + y;
    }
    

    Alternatively, you might consider making x and y be static variables that can only be changed with setter functions. The setter functions for x and y would take care of updating any variables that need to be updated. It's hard to tell whether this approach is worth it without knowing more about your application.

    void change_y(int new_y)
    {
      y = new_y;
      sum = x + y;
    }