GGrewal
GGrewal

Reputation: 177

How do I #define an array in C?

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?

Upvotes: 1

Views: 25075

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753890

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.

Upvotes: 3

Himanshu
Himanshu

Reputation: 1999

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);
}

Upvotes: 2

Related Questions