In the old days of pre-ISO C, the following code would have surprized nobody:
struct Point {
double x;
double y;
double z;
};
double dist(struct
C does not define any way to specify that the compiler must not add padding between the named members of struct Point
, but many compilers have an extension that would provide for that. If you use such an extension, or if you're just willing to assume that there will be no padding, then you could use a union
with an anonymous inner struct
, like so:
union Point {
struct {
double x;
double y;
double z;
};
double coords[3];
};
You can then access the coordinates by their individual names or via the coords
array:
double dist(union Point *p1, union Point *p2) {
double *coord1 = p1->coords;
double *coord2 = p2->coords;
double d2 = 0;
for (int i = 0; i < 3; i++) {
double d = coord2[i] - coord1[i];
d2 += d * d;
}
return sqrt(d2);
}
int main(void) {
// Note: I don't think the inner braces are necessary, but they silence
// warnings from gcc 4.8.5:
union Point p1 = { { .x = .25, .y = 1, .z = 3 } };
union Point p2;
p2.x = 2.25;
p2.y = -1;
p2.z = 0;
printf("The distance is %lf\n", dist(&p1, &p2));
return 0;
}