9

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?

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • The only thing I can think of is preventing it to be usable in template specializations. That's a limitation though. – Pubby Mar 13 '12 at 06:07
  • Of course, if VS2010 supported `constexpr` then it would be: `template constexpr size_t size(T (&)[N]) { return N; }` – Matthieu M. Mar 13 '12 at 07:36

2 Answers2

15

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

Kirill Dmitrenko
  • 3,474
  • 23
  • 31
Asha
  • 11,002
  • 6
  • 44
  • 66
2

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]

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • Bad identifier names... Bad identifier names! – Xeo Mar 13 '12 at 06:30
  • @Xeo, assumed that this is used for library code (OP), which already contains `__` and `_` followed by caps. Copied from the source in the question. – iammilind Mar 13 '12 at 06:31
  • @iammilind: I find this more readable too, however the good thing about the VS way is that it avoids introducing a spurious `struct`. – Matthieu M. Mar 13 '12 at 07:35
  • @MatthieuM., ok. And I can recall that, I [learned this from you](http://stackoverflow.com/questions/8018843/macro-definition-array-size/8021113#8021113) only. :) – iammilind Mar 13 '12 at 09:21