cancel
Showing results for 
Search instead for 
Did you mean: 

gcc int comparison undefined behavior

daniele239955_stm1
Associate II

I found a different behavior, with or without optimization, that I can't explain me.
In the code snippet  below, the value b is 0 if you compile without optimization and 1 with optimization enabled (-O1) (gcc ver 12.3.rev1).
The only apparent difference is having defined zzz3 as volatile.
I obtained this behavior on both F3 and F4 microprocessors. The same code instead works correctly on other architectures both arm and x86, so the result is 0 both for a and b.
Is it a wrong behavior or is it part of an unpredictable behavior that can be overcome by forcing memory barrier or something else?

 

{

static long zzz;

static long zzz2;

static volatile long zzz3;

static int a, b;

 

zzz = 0x80000000-10;

zzz2 = zzz + 1000;

zzz3 = zzz2;

 

a = (zzz - zzz2) > (-1L);

b = (zzz - zzz3) > (-1L);

 

printf("1=failed : a=%d b=%d\n", a, b);

}

 

thanks, for help

1 ACCEPTED SOLUTION

Accepted Solutions
WojRus
Associate

Probably strict overflow rule strike. Use -fwrapv in compiler options to enable signed overflows. Also for testing ARM Cortex-M code on x86 I suggest use GCC options: -march=i386 -m32 to enable pure 32-bit code on PC.

View solution in original post

3 REPLIES 3
Pavel A.
Evangelist III

Which gcc version?

Unfortunately, int overflow is UB and UB is bad. Consider using __builtin_add_overflow,  __builtin_sub_overflow.

gcc ver 12.3.rev1

WojRus
Associate

Probably strict overflow rule strike. Use -fwrapv in compiler options to enable signed overflows. Also for testing ARM Cortex-M code on x86 I suggest use GCC options: -march=i386 -m32 to enable pure 32-bit code on PC.