2

I'm getting some seemingly odd results when I try to update a float3 variable in an OpenCL kernel. Boiling it down:

float3 vel = float3( 0 );   // a
vel = float3( 0, 1, 0 );    // b
vel = (float3)( 0, 2, 0 );  // c

If I print vel after each call with:

if( get_global_id( 0 ) == 0 )
    printf( "[%d]: vel: ( %f, %f, %f )\n", index, vel.x, vel.y, vel.z );

Then I see that a) correctly initializes vel, however b) doesn't do anything. c) works. Does anyone know why I can't update the variable with a new float3 object as I'm doing in b? This is how I'm used to doing it in C++ and glsl. Or possibly a driver bug?

Using OpenCL 1.2 on macbook pro running OS X 10.11.5.

rich.e
  • 3,660
  • 4
  • 28
  • 44

2 Answers2

4

Only c) is a correct way of initialising/using vector types. a) and b) is possibly a bug in Mac implementation (on 2 GPUs and 1CPU I tried that didn't compile).

Few ways of initialising vector type:

float3 vel = (float3)( 1,1,1 );
float3 vel2 = (float3) 1;  // it will be ( 1,1,1 )
float3 vel3 = 1;  // it will be ( 1,1,1 )

More about usage of vector types: spec

doqtor
  • 8,414
  • 2
  • 20
  • 36
2

In C, the comma operator has very specific semantics, as described in detail here (or more briefly here):

(a, b, c) is a sequence of expressions, separated by commas, which evaluates to the last expression c

For your second approach (b), this means that your expression will boil down to float(0), which gives you the same result as in the first approach (a).

Your third approach (c) is making use of specific syntax introduced by OpenCL C which allows for initialising individual elements of a vector, and so doesn't fall into this trap.

Community
  • 1
  • 1
jprice
  • 9,755
  • 1
  • 28
  • 32
  • If I can add to the question: What does `float3( 0, 1, 0 )` boil down to? float3 is not a class, has no constructor, and this is not C++... Also case a) ? how does that even work? – DarkZeros Jun 27 '16 at 10:28
  • 1
    @DarkZeros This is certainly not standard OpenCL C syntax, so likely won't work everywhere (or even anywhere else other than Apple). – jprice Jun 27 '16 at 23:01
  • Sadistic compiler authors don't even warn on the C++ style vector constructor style, silently producing a vector with all components set to the last one specified. ಠ_ಠ – Steven Lu Mar 26 '20 at 20:45