Open In App

errno constant in C++

errno is a preprocessor macro used for error indication. 

The same header that declares errno () also declares at least the following macro constants with values different from zero: 



Below are the programs to implement the working of errno:
Program 1: This program detect error when negative value is passed in log function.  




#include <cerrno>
#include <clocale>
#include <cmath>
#include <cstring>
#include <iostream>
using namespace std;
 
int main()
{
    // log function doesn't take negative value
    // thus it changes value of errno to some positive number
    double not_valid = log(-1.0);
 
    // check if value of errno same as value of EDOM i.e. 33
    if (errno == EDOM) {
        cout << " Value of errno is : " << errno << '\n';
        cout << " log(-1) is not valid : "
             << strerror(errno) << '\n';
    }
    return 0;
}

Output: 

Value of errno is : 33
 log(-1) is not valid : Numerical argument out of domain

 

Program 2: This program detect error when negative value is passed in square root function.




#include <cerrno>
#include <clocale>
#include <cmath>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
    // sqrt function doesn't take negative value
    // thus it changes value of errno to some positive number
    double not_valid = sqrt(-100);
 
    // check if value of errno same as value of EDOM i.e. 33
    if (errno == EDOM) {
        cout << " Value of errno is : " << errno << '\n';
        cout << " -100 is not valid argument for square"
             << " root function : " << strerror(errno) << '\n';
    }
    return 0;
}

Output: 
Value of errno is : 33
 -100 is not valid argument for square root function : Numerical argument out of domain

 

Program 3: This program set errno to ERANGE.




#include <bits/stdc++.h>
using namespace std;
 
// Driver code
int main()
{
    double x;
    double res;
 
    x = 5.000000;
    res = log(x);
 
    if (errno == ERANGE) {
        cout << "Log(" << x << ") is out of range\n";
    }
    else {
        cout << "Log(" << x << ") = " << res << endl;
    }
 
    x = 10.00000;
    res = log(x);
 
    if (errno == ERANGE) {
        cout << "Log(" << x << ") is out of range\n";
    }
    else {
        cout << "Log(" << x << ") = " << res << endl;
    }
 
    x = 0.000000;
    res = log(x);
 
    if (errno == ERANGE) {
        cout << "Log(" << x << ") is out of range\n";
    }
    else {
        cout << "Log(" << x << ") = " << res << endl;
    }
 
    return 0;
}

Output: 
Log(5) = 1.60944
Log(10) = 2.30259
Log(0) is out of range

 


Article Tags :
C++