Is this a VC compiler error? About unsigned integer packaging

I think the C program below will output 1 :

#include <stdio.h> int main() { unsigned int n=18u; while ((n+17u)>=17u) n-=17u; printf("%u\n",n+17u); return 0; } 

But compiled in VC6, Visual Studio 2010 or Visual Studio 2012, all in release mode, the program does not output anything and does not exit.

This is the build code generated by VS2012:

 00BD1000 mov eax,12h 00BD1005 lea eax,[eax-11h] 00BD1008 jmp main+5h (0BD1005h) 

It seems that the compiler has done some optimization and generated an infinite loop.

I think that ((n+17u)>=17u) not always true, because if n==0xFFFF..FF , n+17u up to 16u .

Am I wrong or are the compilers wrong?

+6
source share
2 answers

gcc and clang compile this loop, replacing it with printf constants 1 (using -O3 .)

I think the VC behavior you observe is a mistake: unsigned arithmetic is well defined, and you are correct that the overflow should round to an integer less than 17. Thus, gcc and clang get it right.

+4
source

gcc and clang on macOS:

 #include <stdio.h> int main() { unsigned int n=18u; while ((n+17u)>=17u) { n-= 17u; printf("n=%u %u >= %u\n", n, n+17u, 17u); } printf("%u\n",n+17u); return 0; } 

prints

 n=1 18 >= 17 n=4294967280 1 >= 17 1 

So, n goes β€œbig”, and incrementing to n again makes it β€œsmall”, and the loop ends. I didn’t say too well.

Compiler errors are rare, but I think you found them. Congratulations.

+1
source

Source: https://habr.com/ru/post/957781/


All Articles