Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

  • Print
  • + Share This
Like this article? We recommend

Using Vector Types

Vector types can be operated on as if they were scalars. They can have the standard arithmetic operators (* / ^ | & ~ + - [subtraction and unary minus]) applied to them, with exactly the expected effects. The segments of code in Listings 1 and 2 are semantically equivalent:

Listing 1 Traditional C scalar arithmetic.

int foo[4] = {1,5,7,9};
int bar[4] = {2,3,4,5};
for(unsigned int i=0 ; i<4 ; i++)
{
     bar[i] += foo[i];
}

Listing 2 GCC vector arithmetic.

typedef int v4si __attribute__ ((vector_size (4*sizeof(int))));
v4si foo = {1,5,7,9};
v4si bar = {2,3,4,5};
bar += foo;

The version in Listing 1 uses traditional C scalar arithmetic. Listing 2 uses GCC vector arithmetic, which offers several advantages:

  • It’s easier for the compiler to generate vector instructions.
  • It has fewer lines of code, which typically translates to fewer bugs.
  • It better expresses what’s going on algorithmically.

The third advantage is possibly the most important—someone reading the code can easily see in Listing 2 that the two values are being added. Reading the example in Listing 1 takes a little more effort to extract this information.

  • + Share This
  • 🔖 Save To Your Account