Macro definition ARRAY_SIZE

前端 未结 5 2179
借酒劲吻你
借酒劲吻你 2021-02-19 10:55

I encountered the following macro definition when reading the globals.h in the Google V8 project.

// The expression ARRAY_SIZE(a) is a compile-time constant of t         


        
5条回答
  •  长发绾君心
    2021-02-19 11:45

    latter part will always evaluates to 1, which is of type size_t,

    Ideally the later part will evaluate to bool (i.e. true/false) and using static_cast<>, it's converted to size_t.

    why such promotion is necessary? What's the benefit of defining a macro in this way?

    I don't know if this is ideal way to define a macro. However, one inspiration I find is in the comments: //You should only use ARRAY_SIZE on statically allocated arrays.

    Suppose, if someone passes a pointer then it would fail for the struct (if it's greater than pointer size) data types.

    struct S { int i,j,k,l };
    S *p = new S[10];
    ARRAY_SIZE(p); // compile time failure !
    

    [Note: This technique may not show any error for int*, char* as said.]

提交回复
热议问题