0
#define vec_get(v, x) (*((int *)&(v) + x))

typedef struct {
    int x, y, z;
} Vector3;

/* 
 * rotate around 2d plane origin point
 * example function to demonstrate Vctor3
 */
void
vector3_rotate(Vector3 *vec, Vector3 *axis, int dir)
{
    int i, tmp, *cords[2], **cords_ptr;

    cords_ptr = cords;
    for (i = 0; i < 3; i++) {
        if (!vec_get(*axis, i)) {
    assert(cords_ptr - cords < 2);
            *cords_ptr = &vec_get(*vec, i);
            cords_ptr++;
        }
    }
    assert(cords_ptr - cords == 2);

    tmp = *cords[0];
    switch (dir) {
    case 90:  *cords[0] =  *cords[1]; *cords[1] = -tmp;       break;
    case 180: *cords[0] = -*cords[0]; *cords[1] = -*cords[1]; break;
    case 270: *cords[0] = -*cords[1]; *cords[1] =  tmp;       break;
    }
}

void
vector3_print(Vector3 *vec)
{
    printf("(%d, %d, %d)", vec->x, vec->y, vec->z);
}

int main()
{
    Vector3 x = {1, 2, 3};
    vector3_print(&x);
    printf("\n");
    Vector3 axis = {1, 0, 0};
    vector3_rotate(&x, &axis, 90);
    vector3_print(&x);
}

It seems to work on all compilers but I'm not sure whether casting structure like that (vec_get) is standardized behavior.

I'm supposed to add more details so as you can see, at the bottom there is glorious, magnificent, beautiful main function of type int that is the entry point of this program.

cherrrry9
  • 35
  • 1
  • 4
  • What's the whole point of the `vec_get` macro? Why do you copy pointers to the member variables of `vec` to `cords`? – Some programmer dude Sep 17 '22 at 13:17
  • Also note that [`assert`](https://en.cppreference.com/w/c/error/assert) typically does nothing in release builds. And when enabled it crashes the application. So it's not really a good way to handle run-time validation or bounds checking. – Some programmer dude Sep 17 '22 at 13:18

0 Answers0