Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: what is wrong with abs

Tags:

c++

After a long time trace of my program I finally found that abs is the blameable part of my program. What should I expect from this code? why do I get:

x=0.1

|x|=0

#include <iostream>

int main()
{
    double x=0.1;
    std::cout<<"x="<<x<<std::endl;
    std::cout<<"|x|="<<abs(x)<<std::endl;
    return 0;
}
like image 766
ar2015 Avatar asked Jan 08 '23 17:01

ar2015


1 Answers

You may be wondering "But why I didnt get warning on g++ -g -Wall -Wfatal-errors -Wextra -std=c++11 test.cpp -o ./bin/test -lboost_filesystem -lboost_system?"

Turns out Wall isn't quite "all".

 g++ -g -Wconversion -std=c++11 test.cpp -o tester -lboost_filesystem -lboost_system
test.cpp: In function ‘int main()’:
test.cpp:7:29: warning: conversion to ‘int’ from ‘double’ may alter its value [-Wconversion]
     std::cout<<"|x|="<<abs(x)<<std::endl;
                             ^

clang-3.6's diagnostic is clearer still, and no explicit opt-in required:

$ clang++ -std=c++11 test.cpp -o tester
test.cpp:8:24: warning: using integer absolute value function 'abs' when argument is of floating point type [-Wabsolute-value]
    std::cout<<"|x|="<<abs(x)<<std::endl;
                       ^
test.cpp:8:24: note: use function 'std::abs' instead
    std::cout<<"|x|="<<abs(x)<<std::endl;
                       ^~~
                       std::abs
test.cpp:8:24: note: include the header <cmath> or explicitly provide a declaration for 'std::abs'
1 warning generated.
like image 184
Brian Cain Avatar answered Jan 15 '23 09:01

Brian Cain