Path: utzoo!utgpu!watserv1!watmath!att!pacbell!pacbell.com!ames!ucsd!usc!cs.utexas.edu!uunet!taumet!steve From: steve@taumet.COM (Stephen Clamage) Newsgroups: comp.lang.c Subject: Re: How many elements are in my arrays? Message-ID: <237@taumet.COM> Date: 4 Jun 90 15:42:47 GMT References: <6644.26663D46@puddle.fidonet.org> Reply-To: steve@taumet.UUCP (Stephen Clamage) Organization: Taumetric Corporation, San Diego Lines: 56 In article <6644.26663D46@puddle.fidonet.org> cspw.quagga@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 . If your compiler doesn't support this, it looks like this: : #undef assert /* because multiple includes of 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@taumet.com