Skip to main content
daniele239955_stm1
Associate
January 17, 2025
Solved

gcc int comparison undefined behavior

  • January 17, 2025
  • 2 replies
  • 936 views

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

Best answer by WojRus

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.

2 replies

Pavel A.
Super User
January 18, 2025

Which gcc version?

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

daniele239955_stm1
Associate
January 18, 2025

gcc ver 12.3.rev1

WojRusBest answer
Associate
January 18, 2025

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.