Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of dummy addition in this "number of elements" macro?

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?

like image 804
sharptooth Avatar asked Mar 13 '12 06:03

sharptooth


2 Answers

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

like image 185
Asha Avatar answered Nov 07 '22 16:11

Asha


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]

like image 37
iammilind Avatar answered Nov 07 '22 14:11

iammilind