Quick actions

cmd+k|ctrl+k

Navigation

Languages

Secure countof()

Snippet info

Language

C

Visibility

public

Author

evine

Created

2016-12-22T22:54:45Z

Updated

2016-12-30T00:17:47Z

#include <stdio.h>
#include <assert.h>

#define countof(a) (assert((void *)(a) == (void *)&(a)), sizeof(a) / sizeof(*(a)))

int main(void)
{
    int a[20] = {0};
    int *b = a;
    
    int count_a = countof(a);
    //int count_b = countof(b); // fails
    
    // Passing a function will give incorrect answer. But I find that to be an unlikely mistake.
    int count_main = countof(main);
    
    printf("Array count: %i\n", count_a);
    printf("Function: %i // failure.\n", count_main);
    
    return 0;
}
INFO