While evaluating the below expression in C, output is zero and not infinity. But as per the C Operator Precedence rule, output should be infinity.
double a=1/(1.0/0.0);
printf("a : %.18le\n", a);
Please explain how gcc compiler evaluates this?
While evaluating the below expression in C, output is zero and not infinity. But as per the C Operator Precedence rule, output should be infinity.
double a=1/(1.0/0.0);
printf("a : %.18le\n", a);
Please explain how gcc compiler evaluates this?
The C standard doesn't dictate how doubles handle NaN and Inf numbers, however with gcc the behavior is dictated by IEEE 754 in strict mode: https://en.wikipedia.org/wiki/IEEE_754
from that article:
The standard defines five exceptions, each of which returns a default value and has a corresponding status flag that (except in certain cases of underflow) is raised when the exception occurs. No other exception handling is required, but additional non-default alternatives are recommended (see below).
The five possible exceptions are:
Invalid operation: mathematically undefined, e.g., the square root of a negative number. Returns qNaN by default.
Division by zero: an operation on finite operands gives an exact infinite result, e.g., 1/0 or log(0). Returns ±infinity by default.
- Overflow: a result is too large to be represented correctly (i.e., its exponent with an unbounded exponent range would be larger than emax). Returns ±infinity by default for the round-to-nearest mode.
- Underflow: a result is very small (outside the normal range) and is inexact. Returns a subnormal or zero by default.
- Inexact: the exact (i.e., unrounded) result is not representable exactly. Returns the correctly rounded result by default.
However on some platforms, a ieee 754 compatible floating point unit is not available, and you should either enforce a software floating point library or consult the platforms manual on what happens. For instance, arm's fpu's have a 'RunFast' mode, which disables strict compliance.
Some further information: Do any real-world CPUs not use IEEE 754?
Let's break down the expression:
double a = 1 / (1.0 / 0.0);
first the expression 1.0 / 0.0
is evaluated and the result is +infinity
.
Then following expression is evaluated: 1.0 / +infinity
which results in 0.0
which is the output you get.
The int
1
is promoted to double
prior to the evaluation.
All other answer also apply.
Operations involving infinity, as defined by IEEE-754, follow the same rules, basically, as very very large finite numbers. Dividing 1 by n results in a number that gets closer to zero as n gets larger, so the rounded limit is zero.