On 2006-07-13, Jeff Griglack <grigl...@gmail.com> wrote:

> The compiler should be smart enough that it doesn't need us to make things
> simpler for it.  The important point is readability so the next person who
> has to maintain the code is able to figure out what is going on.

Exactly!

> Heck, I might have to come back to my own code 6 months to a
> year later and want to make it so I can quickly understand it
> again.
>
> One minor point, though.  If you write your macro as:
>
> #define P5_ALARM_ENABLE     (1<<5)
>
> then the precompiler is going to put the "(1<< 5) into your code which is
> going to put a 1 into a register and then shift it over before it even
> applies the mask, an operation that is going to take several cycles.

No, it isn't.  I've been using those sorts of constants for
decades with dozens of compilers.  None of them ever generated
code that loaded a 1 into a register and shifted it (even with
all optimizations turned off).  All of the compilers I've ever
used evaluated constant expressions and just used the resulting
constant in the emitted code.

I usually do something like

#define Bit(n) (1<<(n))

#define WhateverMask  Bit(5)
#define DifferentMask (Bit(4) | Bit(3))

I've used dozens of compilers and I've never seen one that
didn't treat that the same as

#define WhateverMask  0x20
#define DifferentMask 0x18

[And yes, I did look and the generated code.]

> I would think it would be better if you defined things with
> your "or" case:
>
> #define P5_ALARM_ENABLE   (0x20)
>
> which should execute more efficiently.

It generates identical code but is harder to read.

> Or is the optimizer smart enough to recognize this too?

Generally parser handles the evaluation of constant
expressions.

> I don't know, I haven't looked at the code that these would
> generate.

I think you ought to. ;)

When writing embedded stuff, you should always know what
assembly code is going to be generated for a chunk of C code
when you write it.

-- 
Grant Edwards                   grante             Yow!  I'm losing my
                                  at               hair...did it go to
                               visi.com            ATLANTIC CITY??


Reply via email to