How many elements are in my arrays?
Stephen Clamage
steve at taumet.COM
Tue Jun 5 01:42:47 AEST 1990
In article <6644.26663D46 at puddle.fidonet.org> cspw.quagga at p0.f4.n494.z5.fidonet.org (EP Wentworth) writes:
>1) Did the 'offsetof' macro make it into the finals? I notice
Yes.
> it is missing in TurboC 2.0, but present in a couple of other
> compilers that also claim ANSI compatibility.
It is in Turbo C++ 1.0 (which is also a full ANSI C compiler).
>3) I'd like to check at that two arrays have the same number of initializers.
> I'd like this check at compile time, so I'd like to be able to write
>
> #if (num_elems(a) - num_elems(s))
> cause a deliberate compilation error
> #endif
>
> But, uh-huhm, the 'sizeof' and the pointer arithmetic is not permitted
> at pre-processing time. Any way to do this nicely?
Do it at compile time. With any decent compiler, num_elems will be computed
at compile time, the if-expression will evaluate to a constant, and if the
condition is met, the compiler will eliminate the test and the "dead"
code it controls. (If your compiler doesn't work this way, try to get a
better compiler.) Of course, you cannot include illegal code to cause a
compile-time error with this technique.
ANSI corner:
Use the assert macro in the ANSI header <assert.h>. If your compiler
doesn't support this, it looks like this:
<assert.h>:
#undef assert /* because multiple includes of <assert.h> are allowed */
#if defined(NDEBUG)
#define assert(ignore) ((void) 0)
#else
extern void gripe(const char *, int, const char *);
#define assert(expr) \
((expr) ? ((void) 0) : _gripe_(__FILE__, __LINE__, # expr))
#endif
"gripe" just calls printf to print the file, line, and the text of the
test which failed; it then aborts the program.
To use it:
assert(num_elems(a) == num_elems(s));
As noted above, when the test passes no code should be generated for
the assertion.
For production versions, just #define NDEBUG, and the preprocessor
deletes the whole wretched mess.
--
Steve Clamage, TauMetric Corp, steve at taumet.com
More information about the Comp.lang.c
mailing list