SPRUIG8J January 2018 – March 2024
You can specify the values to use for vector initialization or assignment using literals or scalar variables. When all of the components assigned to a vector are constants, the result is a vector literal. Otherwise, the vector's value is determined at run-time. When initializing a vector where each element does not have the same initial value, the constructor initialization idiom should be used as in the example below.
For example, the values assigned to vec_a and vec_b in the following declarations are vector literals and are known during compilation:
short4 vec_a = short4(1, 2, 3, 4);
float2 vec_b = float2(3.2, -2.3);
The following statements initialize all elements of a vector to the same value. In this case, either the "constructor" idiom or the "cast/scalar-widening" idiom can be used.
ushort4 myushort4a = ushort4(1); // constructor syntax (preferred)
ushort4 myushort4b = (ushort4)1; // cast/scalar-widening syntax
Shorter vectors can be concatenated together to form longer vectors. In the following example, two int variables are concatenated into an int2 variable. The value of myvec in the following function is not resolved until run-time:
void foo(int a, int b)
{
int2 myvec = int2(a, b);
. . .
}
The following example concatenates two int2 variables into an int4 variable, which is passed to an external function:
extern void bar(int4 v4);
void foo(int a, int b)
{
int2 myv2_a = int2(a, 1);
int2 myv2_b = int2(b, 2);
int4 myv4 = int4(myv2_a, myv2_b);
bar(myv4);
}