Hello Kevin!

Kevin Schmeichel schrieb:
  Does anyone know the reasoning behind tip # 7 from:

http://mspgcc.sourceforge.net/manual/c1408.html

7. Use int instead of char or unsigned char if you want an 8 bit integer.

This is confusing to me because an int is supposedly 16 bits (http://mspgcc.sourceforge.net/manual/x987.html). Why is it not a good idea to use chars for small ints?

The reason is the C Standard. The arithmetic operations
aren't defined for char type variables. The compiler will
always convert chars to int types for arithmetic operations
and this may result in unexpected results.

For example:

char a;
char b;

a = 0xFF;
b = ~a;
if (b == ~a)
{
// This code might be not reachable because the implicite
// type conversion results in 0x0000 == 0xFF00
// which is always true
}

b = a + 1;
while (b != a + 1)
{
// This loop may never end, because the defined type
// conversion will result in the comparison b != 0x100
// which will be never true.
}

By this, for portability to different compilers and
code safety you need castings to char after each
mathematical operation or you should use an int type.





By the way: Is there a fix for the reported
bug in my email "Code generation error in msp430-gcc version 3.2.3"
(29th of July 2005) in the next version?

The code section was:


/* Calculation / Code generation problem */
/* calculated result is 63936 (-1600) instead of 24000 */

#define MACRO 240U

int Test (void)
{
~  extern unsigned short u16Result;
~  extern unsigned char  u8Value;

~  u16Result = MACRO * u8Value;

~  return (int)u16Result;
}



        Robert Dominicus-Schleutermann

--
Robert Dominicus-Schleutermann      Telefon : +49 36203 96314
Software+Systeme Erfurt GmbH        Telefon : +49 36203 96301
Fichtenweg 8                        Fax     : +49 36203 96333
D-99198 Erfurt-Kerspleben
eMail: mailto:robert.dominicus-schleuterm...@sse-erfurt.de

Reply via email to