How to use of error control functions in C++?

162 Views Asked by At

my source code is bellow :

#include <QtCore/QCoreApplication>
#include <stdio.h>
#include <errno.h>



using namespace std;
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    printf("salam\n");
    int num = 10;
    int ss;
    ss = num / 0;
    printf("%s\n",strerror(errno));

    return a.exec();

}

i want to show my error string for "divide to zero"! but the output is :

salam no such file or directory

please help me how use of errno and errorstring in c++?

2

There are 2 best solutions below

0
On BEST ANSWER

Dividing by zero is just Undefined Behaviour. The language expects you not to write meaningless code like that (and treats you with disdain if you do). Essentially, it renders your entire program meaningless, and anything could happen. You need to check the denominator before the division if there is any chance it could be zero.

The main reason Undefined Behaviour exists in C and C++ is efficiency. The hardware doesn't want to have to check for this special case with no mathematical meaning, and the language doesn't want to have to add the check to every call either. These languages are designed to run very fast in the "good" case.

errno is only set for certain errors when using the Standard Library (and system calls). For instance:

double not_a_number = std::log(-1.0);
std::cerr << std::strerror(errno) << '\n';
0
On

Unfortunately integral division by zero is undefined behaviour in C++. So the runtime could do anything. You've lost control of the program so nothing can help you out.

Your best bet is to check the denominator first and deal with the zero case explicitly: returning non-zero for program failure is idiomatic.