>>>>Frederick Gotham wrote:
>>>>>What's the canonical way to perform an assertion before the
>definition of any objects within a function?
>Flash Gordon wrote:
>>So why not avoid the undefined behaviour the assert is intended to catch
by doing the assert first to it is ensured for of the chance to do its job.
>Bill Pursell wrote:
>How do you do that
without using C90 syntax and allowing declarations to be
mixed with code? eg, you can't do:
int *const p;
assert( f != NULL);
p = f + l; <-- invalid write to read-only p
So you must instead do:
assert(f != NULL);
int *const p = f+l;
Right -- but this uses C99 features (specifically, "variable
declaration/definition almost anywhere", or at least "after
code and without intervening open-brace").
In article <pu************@news.flash-gordon.me.uk>
Flash Gordon <sp**@flash-gordon.me.ukwrote:
>Or if the function is short enough to check by inspection
int *p; /* Note to maintainer, this should never be modified after
initial assignment */
assert( f != NULL);
p = f + l;
Not ideal.
Maybe not ideal, but probably what I would do. Of course, I always
thought that "const" *should* have been defined as a storage-class
specifier (with appropriate modifications to the syntax and semantics
so that you can apply it as well as, e.g., "static"), rather than
a type-qualifier. So my opinion may be suspect. :-)
>Or do as Frederick did in the original post, something like:
int a = (assert(f != NULL), 0);
int *const p = f + l;
Personally, I think that's pretty ugly. It's a little bit better to
group it with the assignment: eg
int *const p = (assert(f!=NULL), f+l);
I can definitely go for this one.
>Or as has also been suggested introducing another scope.
Note that you can even do this by introducing an entire separate
function, e.g.:
void operate_unchecked(T *ptr, size_t len) {
... all the "real work" goes here ...
}
void operate(T *ptr, size_t len) {
/* this is not an assert() because it is delivered in the
final version of the product! */
if (ptr == NULL || len == 0)
panic("bad arguments to operate()");
operate_unchecked(ptr, len);
}
Depending on performance goals and profiling, "operate_unchecked"
can initially be static (and, in C99, explicitly "inline" if you
like), and later exposed (if performance testing proves that the
parameter-checking is a significant performance problem).
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.