error C2440: ‘=’: cannot convert from ‘div_t’ to ‘double’

Home / Uncategorized / error C2440: ‘=’: cannot convert from ‘div_t’ to ‘double’

i’m a beginner and my english is not so well so sorry first. 1. im trying to compile this code and i dont understand the problem- function div returns ‘double’, so why can’t i write this line: "sum= div(x, y);" ? i tried to find the answer here and google it but it doesnt work. 2. beyond that, someone knows what is the solution to this problem- 1>Done building project "test.vcxproj" — FAILED. ? thank you for your answers!
#pragma once

using namespace std;
class DivisionByZero
private:const char* zero_description = "error: division by zero";
public:const char* getZero() {return zero_description;}
void printZero() { cout << getZero() << endl; } }; double div(double x, double y) throw(int, DivisionByZero) { if (x < y) throw - 1; if (y == 0) throw DivisionByZero(); cout << x / y << endl; return x / y; } #include "DivisionByZero.h" using namespace std; int main() { try { int x, y; double sum; cout << "insert x and y values" << endl; cin >> x >> y;
sum= div(x, y);
catch (int a) {
if (a == -1)
cout << "x is smaller than y" << endl; } catch (DivisionByZero& c) { c.printZero(); } catch (...) { cout << "unknown error" << endl; } return 0; }

The problem is that the standard library also contains a div function, which takes two ints and returns a div_t structure. Because you’re passing two ints in the div(x, y) function call, overload resolution picks std::div over your own div function. So you end up trying to assign a div_t structure to a double variable, which results in the error message you’re seeing.

Some compilers also bring div into the top-level namespace (I’m not sure if this is defined by the standard), so even without using namespace std; this might not always work.

The easiest fix (and least confusing for other humans reading your code) is just to rename your own div function to something else.

This is one of the reasons that using namespace std; is frowned upon by some. It’s especially bad practice to put using namespace directives in a header file, because they pollute the scope of any source file including that header. (I’m assuming that the first part of your code snippet is actually the contents of DivisionByZero.h.)
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *