Hi,
I have spotted some piece of code which yields different result on addition of integers and doubles depending if it was performed in the loop or manually (+= vs + bare +).
Here is the (not very clean but short code):
Code:
#include <stdio.h>
#include <limits.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
/* Own power function, when used instead of pow()
the loop returns correct result.
*/
int pow2(int a, int b){
int base = a;
if (!b)
return 1;
while (b--) {
a *= base;
}
return a/base;
}
int main (void) {
int c,d,tmp,tmp2;
for (d = 0, tmp = 0, tmp2 = tmp+1; tmp < 3; tmp++, tmp2++) {
c = 9 * (int)pow(10, tmp) * tmp2;
printf("TEST loop iter %d\n",c);
d += c;
}
// add manually each iteration
int test = (9 * (int)pow(10, 0) * 1) + (9 * (int)pow(10, 1) * 2) + (9 * (int)pow(10, 2) * 3);
printf("Sum added manually: %d, sum in the loop: %d \n", test, d);
return 0;
}
So first of all I have tested this code on both linux and windows machines and the result are different! On windows (mingw) the result is incorrect:
Windows:
Code:
gcc -Wall -O2 tmp.c -o tmp && ./tmp.exe
TEST loop iter 9
TEST loop iter 180
TEST loop iter 2673
Sum added manually: 2889, sum in the loop: 2862
Linux:
Code:
gcc -Wall -O2 tmp.c -o tmp -lm && ./tmp
TEST loop iter 9
TEST loop iter 180
TEST loop iter 2700
Sum added manually: 2889, sum in the loop: 2889
So the as you can see the addition performed manually yields different result on mingw than when it is performed inside the for loop. Why is that?