Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Q about integer multiplication

WSinc
New Contributor I
1,016 Views

Suppose we have:

Integer(4)  A,B

integer(8)  C

C = A* B

YOU WOULD THINK THE COMPILER WOULD BE SMART ENOUGH TO USE THE RIGHT MULTIPLICATION,

BUT IT DOES NOT.  - -  IT GIVES THE WRONG ANSWER.

99.99 PERCENT OF THE TIME, THE ANSWER WOULD NOT FIT INTO A 4 BYTE RESULT-

THAT'S WHY THE INTEGER(8) TYPE IS REQUIRED.

iS THERE A WAY TO FORCE IT TO GIVE THE RIGHT RESULT ?

Probably Dr. Fortran has dealt with this before.

0 Kudos
2 Replies
mecej4
Honored Contributor III
1,016 Views

Define "smart". The Fortran 2008 Standard, all 603 pages of it, does not contain a single instance of "smart". 

The kind of reasoning that you indulged in may also be extended to cases such as

integer :: I, J
real    :: X
..
I = 2
J = 5
...
X = I/J
...

to argue that X should have the -- or a -- representable value closest to 0.4. However X = 0 according to the rules of Fortran.

Here is what the standard does say, in the context of integer expressions and integer multiplication.

7.5.5.2.4 Evaluation of numeric intrinsic operations
  1 The execution of any numeric operation whose result is not defined by the arithmetic used by the processor is prohibited.

 

7.1.9.3

  4 (second item of unnumbered list)

For an expression x1 op x2 where op is a numeric intrinsic binary operator with both operands of the same
type and kind type parameters, or with one real and one complex with the same kind type parameters, the
kind type parameter of the expression is identical to that of each operand.

Your assertion, "99.99 percent of the time, the answer would not fit into a 4 byte result", probably does not apply to 99.99 percent of Fortran programs, which may use integer variables of just default kind (4 byte, these days), multiplying such variables and assuming that the product fits into 4 bytes. Many production compilers do not provide any facilities to check for integer overflow, so it is the programmers' responsibility to avoid integer overflow.

If, in a specific program that you write, you anticipate that multiplication may cause integer overflow, you have to provide code to handle that.

0 Kudos
GVautier
New Contributor II
1,016 Views

The issue is the same in C and I think many other languages.

As mecej4 said, you must force the multiplication to be done in integer(8) if it is possible that the result will overflow integer(4).

C=int8(A)*B

will do the job.

Dont forget also that if the result of an integer(4) operation is between ‭2147483647‬ and ‭4294967295‬, it will interpreted as  negative.

 

0 Kudos
Reply