我如何#在C中定义数组? [英] How do I #define an array in C?
问题描述
以下语法在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); \
} \
}
如果没有,如何在C中定义数组?
If not, how do I define an array in C?
推荐答案
这取决于您如何定义"有效语法".
It depends on how you define 'valid syntax'.
-
C预处理器会将其接受为类似对象的宏.
The C pre-processor will accept it as an object-like macro.
C编译器将不接受输出作为合法C.
The C compiler will not accept the output as legitimate C.
考虑调用:
array[23];
C编译器看到:
[] { for (j=0; j<N_frequencysteps;j++) { array[j] = (function); } } [23];
那是乱码(即使删除了在此处输入代码").
That is gibberish (even with the 'enter code here' removed).
如何在C语言中定义数组?
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
这可以用作:
ARRAY(int, array, 23, j % 9);
(请注意,此初始值设定项取决于宏的实现细节-这不是一个好主意.但是我认为无论如何我都不会使用这样的宏.)如果您使用的是C99模式,则取决于您是否处于这种状态在特定的代码块中有多个(因为它将随后将代码与声明混合)-并且还因为 for
循环中的声明仅在C ++和C99中受支持,而在C90中不支持
(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.
这篇关于我如何#在C中定义数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!