How to determine the length of an array at compile time?

前端 未结 4 1225
一生所求
一生所求 2020-12-18 04:30

Are there macros or builtins that can return the length of arrays at compile time in GCC?

For example:

int array[10];

For which:

相关标签:
4条回答
  • 2020-12-18 05:22
        sizeof(array) / sizeof(int) 
    0 讨论(0)
  • 2020-12-18 05:24
    (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.

    0 讨论(0)
  • 2020-12-18 05:25

    im not aware of a builtin that does this, but i recently used:

    sizeof(array)/sizeof(array[0])

    to do just that

    0 讨论(0)
  • 2020-12-18 05:28

    I wouldn't rely on sizeof since aligment stuff could mess up the thing.

    #define COUNT 10
    int array[COUNT];
    

    And then you could use COUNT as you want.

    0 讨论(0)
提交回复
热议问题