This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

What is this compiler optimization?

Hi,
I found my bug, but I want to understand why the compiler did that!

I use a fonction to clear bits:
CLRBIT(BYTE, MASK);

The following C code:
CLRBIT(aBMCURegisters[REGADDRESS], I2C_SELECT_BIT | DDC_BYPASSN_BIT);

Compile this ASM code:
ANL aBMCURegisters+01H,#07FH

Which is wrong because, the definition of bits are:

#define DDC_BYPASSN_BIT bmBIT2
#define I2C_SELECT_BIT bmBIT7

It's like the compiler only check the first bit of the second argument!

To compile a right code, I need to put the second argument between (), like this:

CLRBIT(aBMCURegisters[REGADDRESS], (I2C_SELECT_BIT | DDC_BYPASSN_BIT));

Compile this ASM code:
ANL aBMCURegisters+01H,#07BH

Please note that the C code use only one line... (no return between args).

Do you know why?
Thanks,
Denis.

Parents
  • You don't give us the definition of CLRBIT, but most likely you have a precedence problem in the macro definition. The fact that an extra level of parens fixes the problem makes me think this is likely.

    As a general rule, macros should always parenthesize their arguments in case an expression is passed in.

    For example, rather than

    #define min(a,b) (a < b) ? a : b

    write

    #define min(a,b) (((a) < (b)) ? (a) : (b))

Reply
  • You don't give us the definition of CLRBIT, but most likely you have a precedence problem in the macro definition. The fact that an extra level of parens fixes the problem makes me think this is likely.

    As a general rule, macros should always parenthesize their arguments in case an expression is passed in.

    For example, rather than

    #define min(a,b) (a < b) ? a : b

    write

    #define min(a,b) (((a) < (b)) ? (a) : (b))

Children