Liste des Groupes | Revenir à cl c |
Hello, Tim.
>
Tim Rentsch <tr.17687@z991.linuxsc.com> wrote:
>Alan Mackenzie <acm@muc.de> writes:>
>Hello, comp.lang.c.>
>
What I want to do is check the validity of (constant) arguments to an
inline function, and output a compiler error if they are invalid.
>
In particular, I have:
>
u32 __always_inline ACM_BITFIELD (u8 a[], int offset, int length)
>
, which is to extract a bitfield of LENGTH bits, starting at bit number
OFFSET in the array of bytes A. OFFSET and LENGTH will be known at
compile time.
>
For the sake of run time efficiency, I wish to impose the restrictions
that either (i) the bitfield will be contained entirely within a byte; or
(ii) the bitfield will be a number of consecutive whole bytes (maximum 32
bits).
>
So, for example, if the code called
>
foo = ACM_BITFIELD (bar, 14, 4);
>
, I would like to output the compiler message "Invalid arguments 14, 4,
to ACM_BITFIELD", since this bitfield straddles two bytes.
>
Is there any way I can do this in C? (Before anybody asks, yes I have
looked at doing it with macros, but that seems impractical, if it's even
possible.)
First, I don't know why you think doing this with macros is
impractical. I knocked out a full macro version without too much
difficulty.
I wanted to generate code conditionally, depending on the macro's
arguments, for efficiency's sake. I don't think this is possible - the C
preprocessor is not Lisp. What I missed was that the compiler's
optimizer will eliminate the superfluous code anyway, so it doesn't
really matter.
Second, if the C you're using has _Static_assert available, the test>
can be done using that. (Richard Damon explains how to get a
similar effect to _Static_assert for C versions before C99.)
_Static_assert will only work within a macro. It doesn't work in an
inline function, whose parameters are not constant expressions, despite
being constants known at compile time. I like the way you've got around
this, below.
Here is an illustrating implementation in C11. I changed the types>
of the arguments offset and length to be unsigned but otherwise it
is just as you outlined. Oh, the error message has an extra pair of
parentheses to avoid problems with macro processing.
Thanks. I'll probably use something like that after my attempts last
night failed. Just that the byte order needs to be little-endian rather
than big-endian. Having unsigned parameters indeed makes sense, seeing
as how it eliminates trouble with negative lengths and offsets.
Les messages affichés proviennent d'usenet.