with a cleaner way to do _countof using a template in C++ 11.
You can also use the template technique to pass a fixed size array to a function, and have the function determine the array size (without needing a 2nd length param, or null terminator element). Similar to strcpy_s(): http://stackoverflow.com/questions/23307268/how-does-strcpy-...
MSVC has a built in _countof: http://stackoverflow.com/questions/4415530/equivalents-to-ms...
While we're talking macros, anyone who reads the g-truc.net article should feel itchy after seeing the countof macro in their example:
#define countof(arr) sizeof(arr) / sizeof(arr[0])
Two problems here:1. The last use of 'arr' doesn't have 'arr' wrapped in parenthesis.
2. The entire expression is not wrapped in parentheses either.
If you write a macro that does any calculation like this, play it safe and put parens around every macro argument and parens around the entire expression too. Otherwise you never know what operator precedence will do to you.
And use do/while wrappers (without a trailing semicolon) where needed: https://kernelnewbies.org/FAQ/DoWhile0
Why?
When reading such code, it means I would have to go and lookup a macro definition. So, there's a clear drawback. What's the benefit that makes it worthwhile?
I guess it could be useful for teams working together on bigger codebases.
2 most IDEs allow simple hover over and see macro definition without having to break much flow.
Otherwise I totally agree with your point.
I mean, you don't go look up the definitions of every function that gets called, every time they are called, right?
But my point with suggesting the macro applies equally to the more traditional sizeof division. I have seen code that divides the two sizeofs every time an array length is needed. I think it's better to put that calculation in a macro so you only do it in one place.
My suggestion to use a macro is not because of any difference in the compiled code, but to improve the readability of the source code.
Instead of writing either of these:
Define this macro instead: Or if you must: And then you can just say: Edit: I used to call this macro 'elementsof', but it seems that 'countof' is a more common name for it and is a bit more clear too - so I'm going to run with that name in the future.