The product of two integers is longer than either of them ...
Thursday, 21 October 2021 04:55 pm![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
The product of two integers is longer than either of them (except when one of them is not much bigger than 1).
Unfortunately computer languages like C and C++ don't really understand or care about this ... which makes it easy to write bugs in these languages ... so there are tools which look at your programs and warn you when this matters.
You use "int" to declare a "standard-sized" integer variable and "long" to declare a bigger one*. So
I have a C++ program which I think has some of these bugs in it. Fortunately there are tools which look at your programs and warn you when this happens. But unless I tell them I know about each multiplication, they will complain about every multiplication. If the language had done the right thing, then
would have always worked, and the tools and I would only need to be picky about lines like
which *will* overflow for some values.
Bah.
* I have ignored the fact that, on computers like mine,
a "long" is the same size as an "int", so you need to use something like "long long" instead.
Oh, and sometimes the value I want to represent cannot be negative, so should I use an "unsigned int"
or perhaps an "unsigned long" aka "long unsigned".
Unfortunately computer languages like C and C++ don't really understand or care about this ... which makes it easy to write bugs in these languages ... so there are tools which look at your programs and warn you when this matters.
You use "int" to declare a "standard-sized" integer variable and "long" to declare a bigger one*. So
long product(int a, int b) {always makes c a variable big enough to contain the product, without overflowing ... but it notes that a and b are "int" and makes the product an "int" as well. So if a*b is big enough, the first few (and hence most important) digits are thrown away - unless you are explicit that you want to keep them:
long c = a * b;
return c;
}
long product(int a, int b) {
long c = (long)(a * b);
return c;
}
I have a C++ program which I think has some of these bugs in it. Fortunately there are tools which look at your programs and warn you when this happens. But unless I tell them I know about each multiplication, they will complain about every multiplication. If the language had done the right thing, then
long c = a * b;
would have always worked, and the tools and I would only need to be picky about lines like
int d = a * b;
which *will* overflow for some values.
Bah.
* I have ignored the fact that, on computers like mine,
a "long" is the same size as an "int", so you need to use something like "long long" instead.
Oh, and sometimes the value I want to represent cannot be negative, so should I use an "unsigned int"
or perhaps an "unsigned long" aka "long unsigned".