1

I have a simple C program that computes (1e200)^2, which should cause a floating-point overflow exception since the largest double is 1e308 or so.

double square(double x){
  return x*x;
}

int main(){
  double x = 1e200;
  double y= square(x);
}

My questions are:

(1) How can you capture the exception via a command line, in such a way that when running the program, the exception can be printed out to the terminal?

(2) How can you capture the exception through injecting additional statements that print out the floating-point exception signal during program execution? For the sake of generality, I would prefer not to use y==inf to achieve this goal.

Thanks.

zell
  • 9,830
  • 10
  • 62
  • 115
  • For non-automated way of checking for errors, see [here](http://stackoverflow.com/q/15655070/478288). – chrisaycock Feb 09 '17 at 16:30
  • something like `if (y == inf) {printf("overflow");}`? – Kami Kaze Feb 09 '17 at 16:40
  • @KamiKaze-- AFIK, implementations are not required to use `inf`. – ad absurdum Feb 09 '17 at 16:58
  • 1
    @DavidBowling You are right he may need to check if `__STDC_IEC_559__` is defined. The floating point standard is not mandatory. But it was more about whether I understood the question correctly. – Kami Kaze Feb 09 '17 at 17:03
  • @chrisaycock Thank you for pointing me to that post. After reading it, I think I should use to solve the problem. – zell Feb 09 '17 at 18:12

1 Answers1

0

I think you are looking for something like this... although this is type char, you could so something similar I believe... and then you can enter whatever printf statement you want within the errno==ERANGE elseif condition.

int check_for_non_number(char *input)
{
    errno = 0;
    char *endptr;
    double xnum = strtod(input, &endptr);
    // IF endptr FOUND A NON-VALID ENTRY AND THAT ENTRY IS NOT THE NEW LINE CHARACTER THEN ITS AN ERROR
    if((*endptr) && (*endptr != '\n'))
    {
        return 1;
    }
    else if (errno == ERANGE)
    {
        printf("OPERAND IS OUT OF RANGE");
        return 1;
    }
    // ELSE IF endptr FOUND A NON-VALID ENTRY AND THAT ENTRY IS THE NEW LINE CHARACTER THEN RETURN 2 TO CHECK IF IT SHOULD BE A NEW LINE
    else if((*endptr) && (*endptr == '\n'))
    {
        return 2;
    }
    else
    {
        return 0;
    }
}
sdepot
  • 41
  • 6