On Fri, 8 Feb 2013, roelof 't Hooft wrote:
> Hi guys, > > I am using a #define to do a calculation during compile > time and load the result in an (8 bit) uart register so > that I can set the baudrate. > > I am using the following in a header file : > > #define crystal 11059200 > #define bd4800 (256 - crystal / 192 * 4800) > > Here the result is 0xef854100 > > #define crystal 11059200 > #define bd4800 (256 - (crystal / 921600)) > > And here the (correct) result is 0xf4 > > Why is it that the multiplication in the first #define fails ? > I have used brackets "()" in numerous places, did typecasts, > split up the #define in multiple parts but all failed on the > multiplication. Multiplication and division have equal precedence and are evaluated left-to-right, so #define bd4800 (256 - crystal / 192 * 4800) is evaluated as #define bd4800 (256 - ((crystal / 192) * 4800)) which gives you the result you see. However, adding parenthesis like this #define bd4800 (256 - crystal / (192 * 4800)) will also give an unexpected result since the integer promotion rules require that 192 * 4800 be computed with an int result, but the arithmetic result is too large to fit in SDCC's 16-bit int. I'd suggest using: #define bd4800 (256 - crystal / (192L * 4800)) > It seems that when I use a multiplication the result stored in > the #define is limited to a signed 16 bit number. > Is this assumption correct ? The #define performs no math; it just defines text for substitution. When the substituted text is evaluated by the next stage of the compiler you need to be aware of the scale of the intermediate results and make sure they will fit within the C specified promoted type (which may not be sufficiently promoted automatically). Erik ------------------------------------------------------------------------------ Free Next-Gen Firewall Hardware Offer Buy your Sophos next-gen firewall before the end March 2013 and get the hardware for free! Learn more. http://p.sf.net/sfu/sophos-d2d-feb _______________________________________________ Sdcc-user mailing list Sdcc-user@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/sdcc-user