Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro definition ARRAY_SIZE

Tags:

c++

c

macros

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 type
// size_t which represents the number of elements of the given
// array. You should only use ARRAY_SIZE on statically allocated
// arrays.

#define ARRAY_SIZE(a)                               \
  ((sizeof(a) / sizeof(*(a))) /                     \
  static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))

My question is the latter part: static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))). One thing in my mind is the following: Since the latter part will always evaluates to 1, which is of type size_t, the whole expression will be promoted to size_t.

If this assumption is correct, then there comes another question: since the return type of sizeof operator is size_t, why is such a promotion necessary? What's the benefit of defining a macro in this way?

like image 707
Lei Mou Avatar asked Nov 05 '11 07:11

Lei Mou


1 Answers

If sizeof(a) / sizeof(*a) has some remainder (i.e. a is not an integral number of *a) then the expression would evaluate to 0 and the compiler would give you a division by zero error at compile time.

I can only assume the author of the macro was burned in the past by something that didn't pass that test.

like image 185
Ben Jackson Avatar answered Sep 24 '22 08:09

Ben Jackson