Search code examples
carithmetic-expressions

Bad arithmetic in c


I'm writing a longer program in C and when I try to run it I get floating point exception error : 8. This is just a snippet of a code due to which I'm getting an error in my main program. Why am I getting an error when a = (1/i+1)?

int main()
{
    double a;
    for(int i = 0; i < 10; i++)
    {
        a = 1/i+1;
        printf("a = %lf",a);

    }
}

Solution

  • The initial value of i is 0 in this expression:

    a = 1 / i + 1;
    

    Since i has int type, you are evaluating a integer division by zero, which invokes undefined behavior.

    It is somewhat misleading that this leads to the message floating point exception error : 8, but perfectly compatible with the notion of undefined behavior.

    Note that you need to change the expression to force evaluation as floating point:

    #include <stdio.h>
    
    int main(void) {
        for (int i = 0; i < 10; i++) {
            double a = 1.0 / i + 1;
            printf("a = %f\n", a);
        }
        return 0;
    }