-1

I need to initialize a fixes size arrays quite often, like so:

for( uint16_t q=0; q<SIZE; q++ ) 
    array[q]=value;

Array is defined as float array[SIZE];

Is there a nicer way of doing this, replacing with a macro or similar?

p.s. Not allowed to use mem___ calls.

Danijel
  • 8,198
  • 18
  • 69
  • 133

2 Answers2

1

C doesn't have built-in way to initialize the entire array to some non-zero value.

If you use GCC, it has Designated Initializers extension. You can use it like:

float widths[] = { [0 ... 99] = 3.14 };

This set all of the elements to 3.14.

Nikita
  • 6,270
  • 2
  • 24
  • 37
0

With preprocessor you can do like this:

#define NMEMBERS(x) (sizeof(x)/sizeof(*(x)))
#define ARRSET(arr, val) \
    do { \
        size_t i; \
        for (i = 0; i < NMEMBERS(arr); ++i) \
            (arr)[i] = val; \
    } while (0)

float array[SIZE], val = 0.67f;
ARRSET(array, val);
freestyle
  • 3,692
  • 11
  • 21
  • 1
    Why would you write such an ugly macro for such a simple thing? Just write a plain for loop, end of story. There's no need to obfuscate the code to oblivion. – Lundin Nov 24 '16 at 14:39
  • Imagine dozen of those loops. This looks nicer: `INITIALIZE(myarr, SIZE, 0.0f);` don't you think. – Danijel Nov 24 '16 at 14:43
  • @Danijel No it looks really bad. C programmers understand C code, they don't understand "my private, secret macro language". There exist no way in C that lets you write this more elegantly than `for(size_t i=0; i – Lundin Nov 24 '16 at 14:44
  • What's ugly? You can make convention about naming of macro-functions so that you would recognize them in the code. What are the problems? The task is simple, I need an array initialization function, the amount of which is known by the compiler. I don't want write simple loop every time when I need that. – freestyle Nov 24 '16 at 15:27
  • 1
    @Danijel You can have two variants: `ARRNSET(arr, size, 0,0f)` and `ARRSET(arr, 0.0f)` – freestyle Nov 24 '16 at 15:46