RTEMS | cpukit/dev/can/can-bittiming.c: Do not use abs() on unsigned values (!726)
Pavel Pisa (@ppisa)
gitlab at rtems.org
Fri Sep 19 21:40:16 UTC 2025
Pavel Pisa commented on a discussion on cpukit/dev/can/can-bittiming.c: https://gitlab.rtems.org/rtems/rtos/rtems/-/merge_requests/726#note_132780
> sample_point = 1000 * ( tseg + CAN_CALC_SYNC_SEG - tseg2 ) /
> ( tseg + CAN_CALC_SYNC_SEG );
>
> - sample_point_error = abs( sample_point_nominal - sample_point );
> + sample_point_error = sample_point_nominal - sample_point;
The removing of the abs would lead to disaster. The result would be finding combination of parameters with maximal negative error. The next test program works correctly
```
#include <stdio.h>
#include <stdlib.h>
volatile unsigned int a = 10;
volatile unsigned int b = 11;
volatile unsigned int c;
int main(void)
{
int d = a - b;
c = abs(a - b);
printf("%d = %d - %d, abs = %u\n",d, a, b, c);
return 0;
}
```
Output
```
-1 = 10 - 11, abs = 1
```
So the `-1` is correctly changed to the `+1`. This effect is necessary to count absolute error.
But you are right that compiling even with mine GCC and `-Wabsolute-value`
```
gcc (Debian 12.2.0-14+deb12u1) 12.2.0
```
ends by
```
gcc -Wall -Wabsolute-value t4.c && ./a.out
t4.c: In function ‘main’:
t4.c:11:7: warning: taking the absolute value of unsigned type ‘unsigned int’ has no effect [-Wabsolute-value]
11 | c = abs(a - b);
| ^~~
```
But output is correct
```
-1 = 10 - 11, abs = 1
```
Test by
```
gcc (Debian 14.2.0-19) 14.2.0
```
gives same warning but the result is the same.
--
View it on GitLab: https://gitlab.rtems.org/rtems/rtos/rtems/-/merge_requests/726#note_132780
You're receiving this email because of your account on gitlab.rtems.org.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.rtems.org/pipermail/bugs/attachments/20250919/f9944b44/attachment.htm>
More information about the bugs
mailing list