Search code examples
c++c++11numeric-limits

Why doesn't it work properly, Numeric_limits


I have a function with two arguments, a vector whose elements are being tested, and a bool variable that we enter as true or false. If we enter true then it is supposed to isolate and place all the elements whose sum of digits is an even number to a new vector (in the same order they came) and return that vector. With false it's the opposite, odd numbers. And you can only use pretty much the things I have already used here, nothing else.

This is how it looks.

std::vector<int> IzdvojiElemente(std::vector<int> v, bool flag){
  std::vector<int> n;
  for(int i(0); i<v.size();i++){
     int suma(0);
     int temp(v[i]);
     if(temp<0) temp*=-1;
     while(temp>0){
        suma+=temp%10;
        temp/=10;
     }

     if(flag && suma%2==0) n.push_back(v[i]);
     if(!flag && suma%2!=0) n.push_back(v[i]);

  }
  return n;
}

And this is one of the main functions for which it doesn't work:

std::vector<int> v1 {1,std::numeric_limits<int>::min(),2, std::numeric_limits<int>::max(),5};
std::vector<int> v2;

v2 = IzdvojiElemente(v1, false);

for(int i=0; i < v2.size(); i++)
   std::cout << v2[i] << " ";

This is what I was supposed to get (as output):

1 -2147483648 5

This is what I got:

1 5

For some reason it either ignores the numeric limits, or doesn't but sorts them with the wrong vector. And I don't know why. In any other cases it works as it should. And maybe it's overflow, but I can't see where.


Solution

  • Yes, this is overflow. Note that in 2's complement representation of signed integers (the common representation on mainstream platforms), the representable range is not symmetric: when the lowest representable number is -2147483648, then the highest representable one is 2147483647.

    -2147483648 * -1 is therefore signed integer overflow and Undefined Behaviour, meaning the program is wrong and anything can happen.

    If you're supposed to handle std::numeric_limits<int>::min() correctly regardless of internal representation, you will have to deal with negative numbers differently (such as computing the digit sum in negative and then just sign-reverse the computed sum).