Visual C++ 10 is shipped with stdlib.h that among other things contains this gem:
template <typename _CountofType, size_t _SizeOfArray>
char (*__countof_helper(UNALIGNED _CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray];
#define _countof(_Array) (sizeof(*__countof_helper(_Array)) + 0)
which uses a clever template trick to deduce array size and prevent pointers from being passed into __countof
.
What's the purpose of + 0
in the macro definition? What problem does it solve?
Quoting STL from here
I made this change; I don't usually hack the CRT, but this one was trivial. The + 0 silences a spurious "warning C6260: sizeof * sizeof is usually wrong. Did you intend to use a character count or a byte count?" from /analyze when someone writes _countof(arr) * sizeof(T).
What's the purpose of + 0 in the macro definition? What problem does it solve?
I don't feel it solves any problem. It might be used to silence some warning as mentioned in another answer.
On the important note, following is another way of finding the array size at compile time (personally I find it more readable):
template<unsigned int SIZE>
struct __Array { char a[SIZE]; }
template<typename T, unsigned int SIZE>
__Array<SIZE> __countof_helper(const T (&)[SIZE]);
#define _countof(_Array) (sizeof(__countof_helper(_Array)))
[P.S.: Consider this as a comment]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With