Question

I'm currently learning C, and I was wondering if there was a really elegant way of a struct variable being able to self assign to it's member variables. i.e.

typedef struct {
    double x; double y; double magn = sqrt(pow(x,2) + pow(y, 2));
} vector2d_t

Clearly this does not work. Is it possible to make some type of pre-proc macro, or wrap the structure within something else so the magnitude is automatically assigned every time the members x, y are changed?

Is there some sort of agreed upon method for doing this, or is it necessary to create a function:

void magnitude(vector2d_t *A){A->magn = sqrt(pow(A->x, 2) + pow(A->y, 2));}

and call it every time you create a new vector2d_t?

Was it helpful?

Solution

Unfortunately this is not supported in C and never will be. C is the kind of programming language that allows you do to almost everything, this means everything manually!

Best you can do is create functions of macros that autoupdate this for you:

void update_x(vector2d_t * v, double x) {
    v->x = x;
    v->magn = sqrt(pow(x,2) + pow(v->y, 2));
}

OTHER TIPS

Your magn is not a property. It is a value depending on two other values. Not only it can't be done automatically, I think that it should never be done automatically. It is yours, as a programmer, choice when and how such value is updated. Lazily, whenever you access it, or proactively, whenever x or y are changed. Or maybe you want to update it periodically, whenever, say, a frame is rendered?

Moreover, logically, mathematically, magn is a function. It is a function with two other parameters. It seems kid of logical to make a function which handles this value somehow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top