问题描述
例如:
$ b $是否有可以在GCC编译时返回数组长度的宏或内置函数? b
int数组[10];
其中:
sizeof(array)== 40
(array)== 10
Update0
我可能会指出在C ++中做这件事很简单。可以构建一个模板,返回 []
中的数字。我确定我曾经在Visual C ++编译器中找到 lengthof
和 dimof
宏/内建函数,但找不到(sizeof(array))/ sizeof(array [0])。
)
或者作为一个宏
<$ p $ (foo)(sizeof(foo)/ sizeof(foo [0]))
int数组[10]; p> #define ARRAY_SIZE
printf(%d%d \ n,sizeof(array),ARRAY_SIZE(array));
40 10
警告:您可以将 ARRAY_SIZE()
宏指向一个数组的指针,并得到一个无任何编译器警告或错误的垃圾值。
Are there macros or builtins that can return the length of arrays at compile time in GCC?
For example:
int array[10];
For which:
sizeof(array) == 40
???(array) == 10
Update0
I might just point out that doing this in C++ is trivial. One can build a template that returns the number inside []
. I was certain that I'd once found a lengthof
and dimof
macro/builtin in the Visual C++ compiler but cannot find it anymore.
(sizeof(array)/sizeof(array[0]))
Or as a macro
#define ARRAY_SIZE(foo) (sizeof(foo)/sizeof(foo[0]))
int array[10];
printf("%d %d\n", sizeof(array), ARRAY_SIZE(array));
40 10
Caution: You can apply this ARRAY_SIZE()
macro to a pointer to an array and get a garbage value without any compiler warnings or errors.
这篇关于如何在编译时确定数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!