2

In my code abs() isnt working but when put in a different code editor it does work. I dont know what to do. Cant find answers anywhere. Please help. Error: ("abs" is ambiguousC/C++(266))

#include <iostream>
#include <cstdlib>

using namespace std;

int main(){

    int x = -1;
    int a = abs(x);

    cout<< a;

}
  • 1
    Is taht a message from your compiler or IDE? – R Sahu Sep 09 '20 at 04:54
  • 1
    Removing the `using` and writing `std::abs` might remove that IDE warning. – Quimby Sep 09 '20 at 04:55
  • Probably related, if not the answer: https://stackoverflow.com/questions/35378761/error-with-abs-in-c – Tas Sep 09 '20 at 04:58
  • 1
    Recommended reading: [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – user4581301 Sep 09 '20 at 05:03

2 Answers2

1

More information will be helpful. There's no need to add "using namespace std" here. You can try to modify "int a = abs(x);" ==> "int a = ::abs(x);"

Paul Wang
  • 97
  • 1
  • 7
  • `#include `, as written in the question, is required to put all the names into `std`, and it is **allowed** to put the names into the global namespace. So `::abs` isn’t required to work. `std::abs` will see all the names. To use `::abs`, the appropriate header is `#include `, which puts all the names into the global namespace and is **allowed** to put the names into `std`. – Pete Becker Sep 09 '20 at 19:26
  • I did above test on Visual Studio 2019(C++17 ), and it works fine. Actually, cstdlib has already included the stdlib.h – Paul Wang Sep 10 '20 at 12:27
  • Yes, that’s the point: it **might** work; it is not **required** to work. Not even in a future version of a compiler for which it now works. – Pete Becker Sep 10 '20 at 14:56
0
#include <iostream>
#include <cstdlib>

using namespace std;

int main(){

    int x = -1;
    int a = fabs(x);

    cout<< a;

}

or


#include <iostream>
#include <stdlib.h>


int main() {

    int x = -1;
    int a = abs(x);

    std::cout << a;

}

harkhuang
  • 32
  • 6