Search code examples
c++integer-overflow

Type that can hold the product of two size_t


I have two size_t integers and need to take their product. In what type should I store the result?

#include <limits>
#include <vector>
#include <iostream>

int main() {
    typedef std::size_t size_t;
    typedef unsigned long long product_t;

    std::vector<double> a(100000);
    std::vector<double> b(100000);

    size_t na {a.size()};
    size_t nb {b.size()};

    product_t prod = na * nb;

    std::cout << prod << std::endl;
}

It looks like gcc defines size_t as an unsigned long long so I am not guaranteed I will be able to store the product... any alternatives?

Edit:

The point here is that I am developing a library that needs to handle vectors of an arbitrary size, compute some statistic on it

double stat = computeStatisticOnVectors(a, b);

and then compute the following:

double result = stat / prod

Solution

  • It really depends on what you are trying to achieve with your code.

    If you are later on going to use the value as a size_t (in other words, for sizing a vector, allocating memory, or some such), then you probably should do some checks that it's not overflowing, but store the value as a size_t. You won't be able to use a bigger type anyway, if the purpose is to create a new object based on the size.

    If you are doing something like "calculating the number of possible combinations from these X vectors", then using a floating point type will probably be "good enough".