In C#, inside a class, we can have variables that are set during the constructor of the type, like such:
class ComplexNumber
{
public double real {get; set;}
public double imag {get; set;}
public double abs {get;}
public Complex Number(double real, double imag)
{
this.real = real;
this.imag = imag;
this.abs = Math.Pow(real*real + imag*imag , 0.5f);
}
}
(I apologize if the C# code is wrong, I haven't written C# in a while and I'm using it purely for an analogy ) During the constructer, the value of 'abs' is set, so I wanted to know if in a C struct, it'd be possible to do the same, even though there is no constructor
typedef struct Comp
{
double real;
double imag;
double abs;
} Comp;
int main(void)
{
Comp z;
z.real = 2.0f;
z.imag = 5.3f;
printf("%f\n" , z.abs);
}
So I'd like to be able to run the code up there and have it return a value for z.abs without ever actually setting it to anything (although it being set to something after both z.real and z.imag are set). Would this be feasible somehow in C?
edit: I have looked as Default values in a C Struct as suggested and in that question, they seem to want a default value for their own type, so a type that is preset, but on my case, what I would like to be able to do is, instead of setting the custom type to a default, every time I set a custom type, one of the attributes inside of it, 'z.abs' would be set using 'z.real' and 'z.imag' instead of having a default value, for examples:
Comp z;
z.real = 4.0f;
z.imag = 3.0f;
After writting this code, z is defined as { 4.0f, 3.0f, null/undefined}, but the last part of it, 'abs' can be calculated using the first two as sqrt(z.real^2 + z.imag^2) and so it's value is 5.0f. So I would want to, after setting the first two numbers, for the third one to be calculated automatically like a constructor in C#, the first example.