On 16 Sep 2004 19:25:40 GMT, Chris Torek <no****@torek.n et> wrote
(reordered slightly for convenience):
In article <news:Xn******* *************** **********@130. 133.1.4>
Mark A. Odell <od*******@hotm ail.com> wrote:I write a lot of drivers and there is inevitably some hardware
register or buffer descriptor field called 'flags' [, usually just
some individual bits]. I [wish I] could get some compile-time type
checking when assigning [named constants] to a flag field ...
Any suggestions?
Ada. :-)
Ada really does have just what you want, *and* is (partly) designed
for use in small embedded systems. In many ways it is a shame we
all use C to program them instead. :-)
Concur. And FWIW Ada has language-defined (standardized) interface to
C. And Fortran and COBOL, which are less likely to be useful in a
lowlevel hardware application. The GNU implementation GNAT also does
C++ (g++) and will "play fairly nicely" in a C main -- I don't know
about others -- but the OP said elsethread he isn't using GNU.
Seriously, the only way to get serious type-checking in C is to
make new types, using C's type-creation mechanism, the "struct".
This is not generally compatible with low-level bit-twiddling.
You can do clever stuff in C++ at compile time with templates, so
that the actual code emitted is just straight integer values going
into the bit-field. This is incredibly ugly, though.
To be clear you can't template a type as such; you would template an
"integer-like" class containing inlined methods, which would as you
say actually compile the same as integers but with added type checks.
Or in C++ you can just use enum types. Unlike C where enum types and
values are just (syntactic sugar for) integers, in C++ they are
distinct types for purposes of overloading and conversion although
they still behave like integer types, and you can't (accidentally)
convert *to* a (different) enum type without a cast. (And also, a
minor point, they can be as wide as long, if that is wider than int.)
- David.Thompson1 at worldnet.att.ne t