tags:

views:

100

answers:

2

Is the following syntax to define an array valid syntax in C?

#define array[] { \
for (j=0; j<N_frequencysteps;j++)  \
{ \
array[j] = (function); \
} \
}

If not, how do I define an array in C?

+3  A: 

It depends on how you define 'valid syntax'.

  • The C pre-processor will accept it as an object-like macro.

  • The C compiler will not accept the output as legitimate C.

Consider an invocation:

array[23];

The C compiler sees:

[] { for (j=0; j<N_frequencysteps;j++) { array[j] = (function); } } [23];

That is gibberish (even with the 'enter code here' removed).


How can you define an array in C?

enum { ARRAYSIZE = 23 };
int array[ARRAYSIZE];
int j;

for (j = 0; j < ARRAYSIZE; j++)
    array[j] = 0;

You could also use an initializer, but you might get compiler warnings unless you are thorough:

int array[ARRAYSIZE] = { 0 };

One more possibility: if you want to define an array and initialize it with calls to a specific function, then you could, I suppose, try:

#define ARRAY(type, name, size, initializer) type name[size]; \
          for (int j = 0; j < size; j++) name[j] = initializer

This could be used as:

ARRAY(int, array, 23, j % 9);

(Note that this initializer depends on an implementation detail of the macro - not a good idea. But I don't think I'd ever use such a macro, anyway.) It depends on you being in C99 mode if you have more than one of these in a particular block of code (since it would then mix code with declarations) - and also because the declaration in the for loop is only supported in C++ and C99, not in C90.

Jonathan Leffler
+1. My preprocessor says `warning: missing whitespace after the macro name`, which at least is a hint that it's a bad idea.
Carl Norum
@Carl: the whole thing is horrid - and yes, it is customary (but not mandatory) to put a space after the name of an object-like macro such as this `array` macro. And the space then emphasizes how horrid it is.
Jonathan Leffler
+2  A: 

This looks really wrong. Why not define array in a normal way?

int array[SIZE];
for (j=0; j<N_frequencysteps;j++)
{  
   array[j] = (function);
}
Himanshu
The '(function)' notation could only be a way of assigning a pointer to function to an array of pointers to functions, assuming 'function' is in fact the name of a function. And presumably the N_frequencysteps should be SIZE or vice versa?
Jonathan Leffler
Oh, and you're right; it is really wrong.
Jonathan Leffler
Yes, SIZE should be larger than or equal to N_frequencysteps
Himanshu