Murad Babayev
Murad Babayev

Reputation: 125

C array vs struct

I am currently developing a OpenGL application. So far everything worked well while programming the API.

For the usual datatypes I use structs. For instance:

struct vec3 {
 GLfloat x;
 GLfloat y;
 GLfloat z;
}

But now I considered to use the same datatypes as simple arrays, for instance

typedef GLfloat vec3[3];

I really like to handle the types as simple arrays since it is easier to access them and I can even use loops to modify their values (for instance in GLfloat matrix[16]) However what kind of annoys me is that C does not allow to return arrays, so I have to provide the storage for operations myself mat4_identity(mat4 output) With a structure I could easily say

mat4 m = mat4_identity() clean and nicely.

My question now is: Which one is better performance wise (of course when having many verticies for instance, I can only think of heavy struct pointer dereferences + acesses) and which one should I actually use in the end for my OpenGL API.

Upvotes: 2

Views: 3631

Answers (1)

If you are using C11, you can have the best of both worlds!

union vec3 {
        struct {
            float x, y, z;
        };
        float xyz[3];
};

Then you can access them either way:

printf("%f %f %f\n", vec.x, vec.y, vec.z);
printf("%f %f %f\n", vec.xyz[0], vec.xyz[1], vec.xyz[2]);

If you are not using C11, you can still do this, but the struct with the three components must be named:

union vec3 {
    struct {
        float x, y, z;
    } components;
    float xyz[3];
}

As for efficiency, arrays are guaranteed to be contiguous (there's no gap between elements) while structs are not, so it may be that a struct wastes more memory. But I doubt that's a problem considering the amount of memory modern computers have.

Also note that while arrays decay to pointers, structs are not guaranteed to do so. Unless the struct fits in a register (vec3 probably doesn't) you should pass pointers to it rather than passing it by value.

Upvotes: 4

Related Questions