如何在编译时确定数组的长度? [英] How to determine the length of an array at compile time?

查看:256
本文介绍了如何在编译时确定数组的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如:


$ 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.

这篇关于如何在编译时确定数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆