8

I ported some code from windows (vs2010) to gcc

a piece of it looks like:

double r1 /* = some value */;
double r2 /* = some value */;
double diff = abs(r1-r2);
std::cerr<<  r1 << ", " << r2 << ", " << diff<< std::endl;

it compiles on gcc (arm-linux-gnueabihf-g++ (Raspbian 6.3.0-18+rpi1+deb9u1) 6.3.0 20170516) with -Wall -Wextra without warnings.

The result is:

0.121, 0.0709839, 0
0.015, 0.131958, 0
0.015, 0.00799561, 0
0.21, 0.00799561, 0
0.182, 0.205994, 0
0.015, 0.00799561, 0

On windows the result is correct. There are double-overloads on the abs functions.

I am not using namespace std;. It seems that under gcc these overloads does not exist in global namespace.

I do not know what exactly the standard says, but i would have expected at least a warning about the double->int-conversion on passing the the difference to the abs function.

Do i have something missed? Why do i not get this warning?

5
  • There are no warnings about implicit conversions in C++. There are no overloads of abs for integer values, consider fabs instead (if you wish to avoid using the STL for some reason.
    – Qubit
    Commented Dec 20, 2018 at 15:11
  • en.cppreference.com/w/c/numeric/math/abs You might want to type std:: before your abs.
    – bipll
    Commented Dec 20, 2018 at 15:16
  • 3
    Funny enough, if you #include <math.h> instead of <cmath> it works properly. Apparently math.h brings everything into global namespace, while cmath selectively brings a single overload. Huh. Commented Dec 20, 2018 at 15:40
  • @bipll yes, this was the mistake, since with vs2010 the overload does exists I got the wrong results - but the main question is, why gcc does not warn about the conversion - even with -Wall and -Wextra Commented Dec 20, 2018 at 17:03
  • gcc is known to be far worse than clang when it comes to reliable warnings. Commented Dec 20, 2018 at 20:29

2 Answers 2

10

abs is a C function that takes one integer and returns another integer.

You want to use the C++ version std::abs instead. Clang would actually warn about the mistake (I even turn it into an error -Werror=absolute-value), not sure if there is a similar flag for gcc (not warning about all conversions, just for abs).

0
4

I think you are looking for the compiler option -Wfloat-conversion or, more general, -Wconversion. Then g++ gives me this warning:

 warning: conversion to ‘int’ from ‘double’ may alter its value [-Wfloat-conversion]
     double diff = abs(r1-r2);

None of the two options is included in -Wall or -Wextra.

It works as long as the conversion is in your code, see here.

1
  • Be aware that -Wconversion is triggered by all conversions, so lots of false positives to be expected. Commented Dec 29, 2018 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.