🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.c.moderated
Article #2444

Interesting compile-time assertion macro

#2444
From: Mike Haertel
Date: Mon, 01 Apr 1996 13:19
46 lines
2057 bytes
Lately I have been writing a device driver for a gadget
with some shared-memory data structures.  In the course
of doing this I've needed to satisfy certain constraints
on staticly allocated sizes and alignments of data
structures.  I hate it when things blow up at run time
that could obviously be avoided at compile time.

So I came up with a compile-time equivalent of <assert.h>:

/*
 * Cause a compile-time error if the asserted expression, which
 * must be a constant expression according to the rules of ANSI C,
 * is false.  Each use of this macro must supply a different
 * identifier for KEY.
 *
 * It works by trying to declare an array of negative size if
 * the asserted expression is false.
 */
#define ASSERT_COMPILE_TIME(EXPR, KEY)                                  \
        struct ASSERT_COMPILE_TIME_##KEY {                              \
                char ASSERT_COMPILE_TIME_##KEY[2*((EXPR) != 0) - 1];    \
        }

Then you can do things like:

struct foo {
	int x;
	int y;
};

ASSERT_COMPILE_TIME(offsetof(struct foo, y) == 4,
	y_is_at_offset_4);

I've found this to be quite useful for error checking in a
complex piece of code which is parameterized by several
#defines, which must together satisfy various constraints.
It's much easier than saying "Warning: FOO*7 + BAR*3 must be
less than 50 or this will not work" in a comment, and gives a
bit of confidence that it would be hard for someone else to
mess up the code accidently.

Anyway, I'm curious.  Has anyone ever seen this particular
hack before?
--
Mike Haertel <haertel@ichips.intel.com>
Not speaking for Intel.
Technical Details
Message-ID: <4jol55$1pi@solutions.solon.com>
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail
From: haertel@ichips.intel.com (Mike Haertel)
Newsgroups: comp.lang.c.moderated
Subject: Interesting compile-time assertion macro
Date: 1 Apr 1996 07:19:33 -0600
Organization: Intel Corporation, Hillsboro, Oregon, USA
Sender: clc@solutions.solon.com
Approved: clc@solutions.solon.com
Message-ID: <4jol55$1pi@solutions.solon.com>
NNTP-Posting-Host: solutions.solon.com