3 ms·
>Here's an example implementation for you. If you're using Visual C++, there's a built-in version. They could literally cut-n-paste this one line into <stddef.h
by andrepd 9y ago
>Here's an example implementation for you. If you're using Visual C++, there's a built-in version. They could literally cut-n-paste this one line into <stddef.h> today.
>#define countof(X) (sizeof(X) / sizeof((X)[0]))
Could they? What if X is empty?
- singingboyo 9y agoStill works. Whether X has any elements is irrelevant, as sizeof doesn't evaluate the expression. Instead, it returns the size of the static type of the expression.
- gruez 9y agoan empty struct has a size of 1 byte. struct Widget{ }; Widget widgets[256]; printf("%d %d", sizeof(widgets), sizeof(Widget)); prints out 256 1 if there are 0 elements, there are no issues because it's 0/x = 0.