-1

I'm having a problem compiling this simple code in VS2017, but the code is working fine in Code Blocks. In VS2017 I've got this error message:

C2382 'abs':redefinition; different exception specifications

Here is the code below:

#include <iostream>
using namespace std;

int abs(int i);
float abs(float f);

int main()
{
    cout << abs(-10) << endl;
    cout << abs(-11.0f) << endl;
    return 0;
}
int abs(int i)
{
    cout << "Using integer abs()\n";
    return i<0 ? -i : i;
}
float abs(float f)
{
    cout << "Using float abs()\n";
    return f<0.0f ? -f : f;
}
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
Omar Alesharie
  • 251
  • 1
  • 2
  • 6

1 Answers1

1

The reason you are getting an error is because there are already a set of functions called abs in the standard library, which would normally have to be accessed with std::, but using namespace std removes that qualifier, creating a name collision between all the functions. Thus, you should either change the name of your functions to something like myAbs, or remove the using namespace std. An even better change would be to both remove the using statement and rename the function.

Your code exhibits a key reason to why using namespace std should be avoided, since it can cause namespace collisions and unnecessary confusion.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88