Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the MSVC _count_of implementation add 0 to the result of sizeof? [duplicate]

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?

like image 296
Kirill Dmitrenko Avatar asked Dec 18 '19 14:12

Kirill Dmitrenko


1 Answers

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;
}
like image 172
Adrian Mole Avatar answered Nov 08 '22 16:11

Adrian Mole