bens_dad: (Default)
[personal profile] bens_dad
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
long product(int a, int b) {
   long c = a * b;
   return c;
}
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 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".
(will be screened)
(will be screened if not validated)
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

bens_dad: (Default)
bens_dad

May 2025

S M T W T F S
    12 3
45678910
11121314151617
18192021222324
25262728 293031

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Saturday, 14 June 2025 06:52 pm
Powered by Dreamwidth Studios