|
|
|
![]() |
|
|||||||
|
||||||||
![]() |
| Thread Tools | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
A strange occurence..
I'm a student at VCU and near the shipping deadline I went out to a school in the Richmond area that my friend mentors to help them with their programming issues. Apparently the compiler is as wonderful as last year.. and here's a solution for a problem they had...
The original code went something to the tune of: Code:
if(calib) {
offset01 = p1_y - 128;
calib=0;
}
if(p1_y - offset01 > 254)
pwm01 = 254;
else if(p1_y - offset01 < 0)
pwm01 = 0;
else
pwm01 = p1_y - offset01;
This should be the fix: Code:
if(calib) {
offset01 = p1_y - 128;
calib=0;
}
if( ((signed int) p1_y) - offset01 > 254)
pwm01 = 254;
else if( ((signed int) p1_y) - offset01 < 0)
pwm01 = 0;
else
pwm01 = ((signed int) p1_y) - offset01;
|
|
#2
|
|||||
|
|||||
|
Re: A strange occurence..
That programmer fell victim to a deliberate feature of the compiler.
Rather than do calculations at the ANSI specified int size, the PIC compiler deliberately tries to keep the sizes used in calculations as small as possible to save valuable space. It will do calculations at the largest type used in the calculation. If they are all char then the calculations will be done in char and the program will suffer from any overflows that might occur during the intermediate calculations. You can override the default and force the compiler to do promote all calculations to at least integer. See section 2.7.1 of the MPLAB C18 C Compiler User’s Guide, http://ww1.microchip.com/downloads/en/DeviceDoc/C18_UG__51288e.pdf “2.7 ISO DIVERGENCES 2.7.1 Integer Promotions ISO mandates that all arithmetic be performed at int precision or greater. By default, MPLAB C18 will perform arithmetic at the size of the largest operand, even if both operands are smaller than an int. The ISO mandated behavior can be instated via the -Oi command-line option. For example: unsigned char a, b; unsigned i; a = b = 0x80; i = a + b; /* ISO requires that i == 0x100, but in C18 i == 0 */ Note that this divergence also applies to constant literals. The chosen type for constant literals is the first one from the appropriate group that can represent the value of the constant without overflow.” |
![]() |
| Thread Tools | |
| Display Modes | Rate This Thread |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Strange Auto Problem | NotQuiteFree | Programming | 6 | 20-02-2005 17:12 |
| Strange 16 bit MS-DOS subsystem error | Crazy_Ed | Programming | 6 | 18-03-2004 14:31 |
| strange error | Anthony Kesich | Programming | 2 | 25-02-2004 18:55 |
| Linux and the New R/C and Strange ideas... | Venkatesh | Programming | 7 | 28-10-2003 23:54 |
| Strange Serial Input | Adam Shapiro | Programming | 4 | 31-01-2003 02:01 |