Macro definition ARRAY_SIZE

前端 未结 5 2187
借酒劲吻你
借酒劲吻你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-19 11:43

    The second part wants to ensure that the sizeof( a ) is divisible of by sizeof( *a ).

    Thus the (sizeof(a) % sizeof(*(a))) part. If it's divisible, the expression will be evaluated to 0. Here comes the ! part - !(0) will give true. That's why the cast is needed. Actually, this does not affect the calculation of the size, just adds compile time check.

    As it's compile time, in case that (sizeof(a) % sizeof(*(a))) is not 0, you'll have a compile-time error for 0 division.

提交回复
热议问题