I've been reading the implementation of the _countof
macro in MSVC and found a detail I can't explain. It's implemented via a __crt_countof
macro which on C++ is expanded to (sizeof(*__countof_helper(_Array)) + 0)
(here's the relevant code from the header). Why is + 0
there? What would go amiss without it?
The + 0
is added to prevent a potential occurrence of the Most Vexing Parse! Without it, an expression like sizeof(*__countof_helper(_Array))
could be taken as a function declaration in some circumstances.
EDIT: I'm currently trying to work up an example context (as per request in the comment). In the meantime, this much-simplified 'equivalent' (something I have actually encountered) may be helpful:
#include <iostream>
#include <vector>
int main() {
int num = 2;
// std::vector<char> vec(size_t(num)); // Won't compile - Most Vexing Parse
std::vector<char> vec(size_t(num) + 0); // Compiles - no longer a func decl!
vec[0] = 'a';
vec[1] = 'b';
std::cout << vec[0] << ' ' << vec[1] << std::endl;
return 0;
}
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