c++ - Why does std::abs return signed types -


i'm getting warning signed vs. unsigned comparison when i'm comparing std::abs(int) against unsigned. , indeed, std::abs returns signed values. why choice made? have solved problem of negative values absolute value cannot represented in signed type.

and then, there cleaner (i.e., without cast) avoid warnings?

#include <cassert> #include <cstdlib>  // max(1, lhs + rhs). (lhs must > 0) unsigned add(unsigned lhs, int rhs) {   return     (0 < rhs || static_cast<unsigned>(-rhs) < lhs      ? rhs + lhs      : 1); }  int main() {   assert(add(42, -41) == 1);   assert(add(42, 0) == 43);   assert(add(42, 1) == 43);   assert(add(42, -51) == 1); } 

the short answer done return type of abs same input type. want, of time.

mostly, when calling abs, you're dealing equation elements of same type (or you'd warnings) , want use magnitude of variable in equation. doesn't mean want change type of 1 of variables in equation. give kind of issues/warnings you're mentioning.

so, in short, more common , more natural want same input , output type when asking absolute value of signed variable. magnitude of value isn't commonly used index.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

node.js - Bad Request - node js ajax post -

uitableview - Create and use custom prototype table cells in xamarin ios using storyboard -