[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: C programming question



On 20100413_193540, Robert Baron wrote:
> What a great little learning project.
> 
> My suggestion is to work out a simpler version of what you are trying to do:
> 
> typedef struct {
>     unsigned short rec_type;
>     long data;
> } type1;
> 
> typedef struct {
>     unsigned short rec_type;
>     char data[4];
> } type2;
> 
> .....
> some_type *chunk_of_mem;
> 
> long a = ((type1 *) chunk_of_mem)->data;
> char *b = ((type2 *) chunk_of_mem)->data;
> .....
> 
> and either work out how to get the union syntax or casting.  Both
> should work equally well.  One may be easier to work though with you
> compiler.
> 
> Rob.

C is a remarkably flexible, close to the hardware, language.  For many
years the C-way was, to the eyes of the non-expert, distinctly
non-obvious --- to the point that there was an open contest with
prizes awarded for the most obfuscated example of C code. The prizes
went to the code for which the judges were most surprised on seeing
it run after they read the code and tried to figure out what would
happen when it was run.

But the union construct is now there in the language in order to allow
the professional practitioner to make his code slightly less
obfuscated. I think you should use it. It will stick out in the
displayed text as a warning to future readers of your code that
something dangerous is being done. And it will not ever become an
out-of-date comment that can be safely ignored by that future reader.

You may be that future reader of your code who will appreciate what
you have done by using it.

-- 
Paul E Condon           
pecondon@mesanetworks.net


Reply to: