C - How to access elements of vector using GCC SSE vector extension

前端 未结 3 361
鱼传尺愫
鱼传尺愫 2020-12-15 11:36

Usually I work with 3D vectors using following types:

typedef vec3_t float[3];

initializing vectors using smth. like:

vec3_         


        
相关标签:
3条回答
  • 2020-12-15 11:51

    Note that gcc 4.6 now supports subscripted vectors:

    In C vectors can be subscripted as if the vector were an array with the same number of elements and base type. Out of bound accesses invoke undefined behavior at runtime. Warnings for out of bound accesses for vector subscription can be enabled with -Warray-bounds.

    0 讨论(0)
  • 2020-12-15 11:59

    You are forgetting that you need to reinterpret a as array of floats. Following code works properly:

    int main(){
        v4sf a,b,c;
        a = (v4sf){0.1f,0.2f,0.3f,0.4f};
        b = (v4sf){0.1f,0.2f,0.3f,0.4f};
        c = (v4sf){0.1f,0.2f,0.3f,0.4f};
        a = b + c;
        float* pA = (float*) &a;
        printf("a=[%f %f %f %f]\n",pA[0], pA[1], pA[2], pA[3]);
        return 0;
    }
    

    P.S.: thanks for this question, I didn't know that gcc has such SSE support.

    UPDATE: This solution fails once arrays got unaligned. Solution provided by @drhirsh is free from this problem.

    0 讨论(0)
  • 2020-12-15 12:03

    The safe and recommended way to access the elements is with a union, instead of pointer type punning, which fools the aliasing detection mechanisms of the compiler and may lead to unstable code.

    union Vec4 {
        v4sf v;
        float e[4];
    };
    
    Vec4 vec;
    vec.v = (v4sf){0.1f,0.2f,0.3f,0.4f};
    printf("%f %f %f %f\n", vec.e[0], vec.e[1], vec.e[2], vec.e[3]);
    

    0 讨论(0)
提交回复
热议问题