Unary and Binary Operators for Vectors

When unary operators (such as negate: -) and binary operators (such as +) are applied to a vector, the operator is applied to each element in the vector. That is, each element in the resulting vector is the result of applying the operator to the corresponding elements in the source vector(s).

Table 5-7 Unary Operators Supported for Vector Types

Operator Description
- negate
~ bitwise complement
! logical not (integer vectors only)

The following example declares an int4 vector called pos_i4 and initializes it to the values 1, 2, 3, and 4. It then uses the negate operator to initializes the values of another int4 vector, neg_i4, to the values -1, -2, -3, and -4.

int4 pos_i4 = (int4)(1, 2, 3, 4); int4 neg_i4 = -pos_i4;

Table 5-8 Binary Operators Supported for Vector Types

Operator Description
+, - , *, / arithmetic operators (also supported for complex vectors)
=, +=, -=, *=, /=, assignment operators
% modulo operator (integer vectors only)
&, |, ^, <<, >> bitwise operators
>, >=, ==, !=, <=, < relational operators
++, -- increment / decrement operators (prefix and postfix; integer vectors only; also supported for the real portion of complex vectors)
&&, || logical operators (integer vectors only)

The following example uses the =, ++, and + operators on vectors of type int4. Assume that the iv4 argument initially contains (1, 2, 3, 4). On exit from foo(), iv4 will contain (3, 4, 5, 6).

void foo(int4 iv4) { int4 local_iva = iv4++; /* local_iva = (1, 2, 3, 4) */ int4 local_ivb = iv4++; /* local_ivb = (2, 3, 4, 5) */ int4 local_ivc = local_iva + local_ivb; /* local_ivc = (3, 5, 7, 9) */ }

The arithmetic operators and increment / decrement operators can be used with complex vector types. The increment / decrement operators add or subtract by 1+0i.

The following example multiplies and divides complex vectors of type cfloat2. For details about the rules for complex multiplication and division, please see Annex G of the C99 C language specification.

void foo() { cfloat2 va = (cfloat2) (1.0, -2.0, 3.0, -4.0); cfloat2 vb = (cfloat2) (4.0, -2.0, -4.0, 2.0); /* vc = (0.0, -10.0), (-4.0, 22.0) */ cfloat2 vc = va * vb; /* vd = (0.4, -0.3), (-1.0, 0.5) */ cfloat2 vd = va / vb; ... }