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++?
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';