4

Inside my kernel, I need an array of accumulators.

__kernel myKernel(...)
{
    float accum[SIZE] = {};

    for(i=0; i<ITER; ++i) {
       accum[...] += ...
    }

    ...
}

In C, the = {} would initialize the array for me to be filled with 0, but I'm not sure if that's the case in OpenCL? Do I need something like the following, or is it a waste of cycles?

float accum[SIZE];
for(int i=0; i<SIZE; ++i) accum[i] = 0;
Nicu Stiurca
  • 8,747
  • 8
  • 40
  • 48
  • None of the variables in your example are statically allocated. They are all private (or automatic). I'd suggest titling this "Does OpenCL support array initializers?" or something similar. – Tim Dec 06 '14 at 19:44
  • @Tim Good point, thanks. – Nicu Stiurca Dec 08 '14 at 13:52
  • Also FWIW I'ved used zero initializers in Intel GPU OpenCL implementation (={0}) successfully. I recall running into a random size limit though (compile error if too big). – Tim Dec 08 '14 at 17:25

1 Answers1

5

OpenCL C is a derivative of the ISO/IEC 9899:1999 C language specification, aka C99. In both specifications, yes, = { 0 } will zero-initialize an array (note the 0, empty initializer lists are not allowed in C).

In practice, some implementations may also clear the device private's and/or local memory with zeroes before you launch a kernel, but this is not a behavior you can rely on.

Community
  • 1
  • 1
user703016
  • 37,307
  • 8
  • 87
  • 112
  • I know OpenCL is a C derivative, but can you point to somewhere in the OpenCL spec that explicitly requires this initialization? I ask because I'm worried this requirement might have been scrapped in order to simplify the OpenCL spec/drivers. – Nicu Stiurca Dec 08 '14 at 13:55
  • The OpenCL spec itself doesn't cover that precise point and simply redirects you to the ISO C99 spec (somewhere in the first few pages, if memory serves). Therefore C99 rule applies: you are not *required* you to initialize variables, but if you don't, then the contents are undefined. – user703016 Dec 08 '14 at 14:20
  • 1
    Hate to necro this, but I don't think this is actually true: this so answer (http://stackoverflow.com/questions/17589533/is-an-empty-initializer-list-valid-c-code/17589839#17589839) shows that empty intializers are not allowed. Haven't found something relevant in the spec, but he makes a good argument. Maybe the OpenCL C specification has something different to say about this? – bobismijnnaam Jun 07 '16 at 09:57
  • @bobismijnnaam Good point, I have edited my answer. I was thinking in C++, which does allow empty initializers. – user703016 Oct 04 '16 at 05:17