BUILD_BUG_ON_ZERO

Dave Hylands dhylands at gmail.com
Fri Feb 25 11:33:53 EST 2011


Hi Zhang,

On Fri, Feb 25, 2011 at 3:50 AM, Zhang Meng <jammy.linux at gmail.com> wrote:
> Hi ~List,
>
> Could anybody explain the macro below? what does it mean?
>
> Thanks in advance.
>
> #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))

This is also known as a compile time assert. I think that this
particular variant has to be used inside a function.

! is just negation and produces a zero or 1 result. !! just does it
twice, so that a non-zero value coming in becomes 1, and a zero value
remains as zero.

If e evaluates to false (zero) then -!!(e) evaluates to zero;
if e evaluates to true (non-zero) then -!!(e) evaluates to -1.

Declaring a bit field with a size of -1 will cause a compiler error.
I'm actually surprised that declaring a bitfield of size 0 works.

The typical declarations of this I've seen usually use arrays and
arrange for the size to be -1 or 1 (which is generally more portable).
When you use the array style declaration, you can use it outside a
function as well.

Dave Hylands



More information about the Kernelnewbies mailing list