Thread: Very weird issue with double to int conversion inside the loop

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User MartinR's Avatar
    Join Date
    Dec 2013
    Posts
    200

    Lightbulb Very weird issue with double to int conversion inside the loop

    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?
    Last edited by MartinR; 07-08-2021 at 02:33 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Weird Conversion Error
    By EverydayDiesel in forum C++ Programming
    Replies: 1
    Last Post: 06-08-2019, 08:41 PM
  2. Help - Collect data from Switch loop inside While loop
    By James King in forum C Programming
    Replies: 15
    Last Post: 12-02-2012, 10:17 AM
  3. Some weird issue.
    By dbzx in forum C Programming
    Replies: 7
    Last Post: 04-12-2009, 04:10 PM
  4. double conversion
    By shuo in forum C++ Programming
    Replies: 3
    Last Post: 01-21-2008, 12:11 AM
  5. Replies: 3
    Last Post: 06-11-2002, 12:57 PM

Tags for this Thread