Hello all, I've just started to learn C++ since I have a bit of time on my hands. I was doing an exercise, learning functions and built a multiplier (very basic, enter 2 numbers and here is the result) strange thing, if the numbers you enter are very high, I get this: the product of your two numbers is 373441392, is there a reason it's this number, anyone know?

#include <iostream>

using namespace std;

int mult ( int x, int y );

int main()
{
    int x;
    int y;

    cout<<"Please input two numbers to be multiplied (separated by a space) : ";
    cin>> x >> y;
    cin.ignore();
    cout<<"The product of your two numbers is "<< mult ( x, y ) <<"\n";
    cin.get();
}

int mult ( int x, int y )
{
    return x * y;
}

Dani AI

Generated

— that strange number is a symptom of integer overflow. pointed you in the right direction: your program used a type that could not hold the true product, and the multiplication wrapped to a different value on your machine. One important caveat: the C++ standard says signed integer overflow is undefined behavior, so the exact wrong number you saw (373441392) is what your compiler/architecture happened to produce — other compilers or platforms might behave differently.

Quick checks to run on your machine:

#include <iostream>
#include <limits>

std::cout << "sizeof(int) = " << sizeof(int) << " bytes\n";
std::cout << "INT_MAX = " << std::numeric_limits<int>::max() << '\n';

That tells you how big int is and what its maximum value is on your build.

Options to fix the problem

  • Use a wider fixed-width type (long long or int64_t) if your values fit in 64 bits. Example:
    #include <cstdint>
    int64_t a, b;
    std::cin >> a >> b;
    std::cout << (a * b) << '\n';
  • Detect overflow explicitly. On GCC/Clang you can use __builtin_mul_overflow to detect an overflow at runtime and handle it.
  • For arbitrarily large integers, use a multiprecision library (for example Boost.Multiprecision cpp_int) so results never silently wrap.

Checklist: decide the maximum range you need, pick a type that covers it (or use multiprecision), and add runtime checks if incorrect values must be detected. Do not rely on signed wrap-around — it is not guaranteed by the language.

The reason is there is a maximum value that an integer can hold -- the maximum is declared in the header file limits.h that is supplied by your compiler. What you are seeing is called numeric overflow.

If you need bigger numbers then use a bigger integer, such as "long long", which holds about twice as many digits as an int or long. There are no standard C or C++ data types that will hold an infinite number of digits.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.