Article View: comp.lang.c.moderated
Article #2460Re: Interesting compile-time assertion macro
From: Mike Coffman
Date: Tue, 02 Apr 1996 01:59
Date: Tue, 02 Apr 1996 01:59
52 lines
2559 bytes
2559 bytes
Mike Haertel wrote in comp.lang.c.moderated:
> 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]; \
> }
Mike:
I like the principle of protecting the users of source code that I write
from the mistakes they make adjusting the parameters to their
application.
I usually use the sequence:
#if test_condition
#error error message
#endif
but, as you can see, this takes three lines to invoke to your one.
The only overhead/disadvantage to your technique is that once I get my
code to compile successfully I have a number of structures composed of
one element character arrays taking up a little space.
My editorial comment:
This is one more instance where the implementation of the C preprocessor
has caused additional work or inconvenience. If a #define could be
defined to contain additional preprocessing directives, my #if, #error,
#endif sequence could be defined as a macro, and invoked as easily as
Mike's ASSERT_COMPILE_ASSERT(EXPR, KEY) macro.
The improvement would be a more obvious macro (test a condition and
produce and error message) rather than relying on Mike's clever but
mildly
obscure technique of conditionally producing an error message by
defining an array with a negative dimension, which also has the slight
side effect of using a small amount of storage for each successful
compile
time assert macro.
Mike Coffman
coffman@cat.com
*** My opinions only and not necessarily those of my employer. ***
Technical Details
Message-ID:
<4jq1lg$a67@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4jol55$1pi@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail From: Mike Coffman <coffman@cat.com> Newsgroups: comp.lang.c.moderated Subject: Re: Interesting compile-time assertion macro Date: 1 Apr 1996 19:59:12 -0600 Organization: Caterpillar Inc. Sender: clc@solutions.solon.com Approved: clc@solutions.solon.com Message-ID: <4jq1lg$a67@solutions.solon.com> References: <4jol55$1pi@solutions.solon.com> NNTP-Posting-Host: solutions.solon.com X-Mailer: Mozilla 2.0 (X11; I; HP-UX A.09.05 9000/715)