Quick actions

cmd+k|ctrl+k

Navigation

Languages

Vector and Union

Snippet info

Language

C

Visibility

public

Author

evine

Created

2016-01-20T03:58:36Z

Updated

2016-01-20T05:01:56Z

#include <stdio.h>

typedef union
{
    struct
    {
        unsigned int x , y;
    };
    
    unsigned int e[2];
}v2;

typedef union
{
    struct
    {
        unsigned int x , y , z;
    };
    struct
    {
        unsigned int r , g , b;
    };
    
    v2 xy;
    unsigned int e[3];
}v3;


typedef union
{
    struct
    {
        unsigned int x , y , z , w;
    };
    struct
    {
        unsigned int r , g , b , a;
    };
    
    v3 xyz;
    v3 rgb;
    unsigned int e[4];
}v4;

// v2add , v3add , v4add
#define vXaddDefine(Elements)               \
void v##Elements##add(unsigned int *Result,unsigned int *First,unsigned int *Second)    \
{                                           \
    for(int i = 0;                          \
        i < Elements;                       \
        i++)                                \
        Result[i] = First[i] + Second[i];   \
}

vXaddDefine(2)
vXaddDefine(3)
vXaddDefine(4)

// vAdd, pass in vector size
void vAdd(unsigned int *Result,unsigned int *First,unsigned int *Second, int Elements)
{                                           
    for(int i = 0;                          
        i < Elements;                       
        i++)                                
        Result[i] = First[i] + Second[i];   
}

int main() {

    v4 aero = {};
    aero.x = 5;
    aero.y = 3;
    aero.z = 9;
    aero.w = 100;
    
    v4add(aero.e,aero.e,aero.e);    //Equivalent functions
    vAdd(aero.e,aero.e,aero.e,4);

    printf("%i\n",aero.x);
    printf("%i\n",aero.y);
    printf("%i\n",aero.z);
    printf("%i\n",aero.w);
    
    printf("\n");
    v2 llll;
    
    llll.x = 1;
    llll.y = 2;
    
    printf("v2.x %i\n",llll.x);
    printf("v2.y %i\n",llll.y);
    printf("v2.e[0] %i\n",llll.e[0]);
    printf("v2.e[1] %i\n",llll.e[1]);
    return 0;
}
INFO