C Standard Library

C <errno.h> - ERANGE constant



The C <errno.h> ERANGE is macro constant which represents a range error. The range error occurs if the output of a function is outside the range (result is too large) and sets errno to ERANGE.

The range of values that can be represented with a variable is limited. For example, mathematical functions such as pow() can easily outbound the range representable by a floating point variable, or functions such as strtod() can encounter sequences of digits longer than the range representable values. In these cases, errno is set to ERANGE.

The error messages associated with values of errno can be obtained using strerror() or directly printed using function perror().

In the <errno.h> header file, it is defined as follows:

#define ERANGE /* implementation-defined */

Example 1:

The example below shows the usage of ERANGE macro constant.

#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <string.h>

int main(){
  double result = log(0.0);
  printf("%f\n", result);

  if (errno == ERANGE) {
    printf("log(0.0) failed: %s\n", strerror(errno));
  }
}

The output of the above code will be:

-inf
log(0.0) failed: Numerical result out of range

Example 2:

Consider one more example where this macro constant is used to handle a out of range condition.

#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <string.h>

int main(){
  double result = pow(100000, 100000);
  printf("%f\n", result);
  
  if (errno == ERANGE){
    fprintf(stderr, "Value of errno: %d\n", errno);
    perror("Error printed by perror");
    fprintf(stderr, "Error executing function: %s\n", strerror(errno));
  }
}

The output of the above code will be:

inf

Value of errno: 34
Error printed by perror: Numerical result out of range
Error executing function: Numerical result out of range

❮ C <errno.h> Library