Multiplying LongInts. Expression of the form: Int64Var := LongIntVar * LongIntVar

老子叫甜甜 提交于 2019-12-12 03:55:48

问题


I always thought it was part of the design philosophy in Pascal, that it looked at both the right and left hand sides of an expression when deciding what format/precision to use for an operation. So that, unlike C where an expression like,

Float_Var = 1/3

results in a value of 0.0 for Float_Var, Pascal always gets this stuff right. :)

So I was kind of surprised when I went to multiply two LongInts (32 bit) to give an Int64 result and found I was getting anomalous results. I had to get all C like and use,

Int64_Var := Int64(LongIntVar1) * LongIntVar2

to make it work correctly. (BTW. This was under Delphi, various versions tested, but all win32).

I was just wondering if this is an exceptional case in Delphi/Pascal? Or are there other examples where the usual Pascal way, using the types on both sides of an expression to decide on how the operation is performed, doesn't hold.


回答1:


I always thought it was part of the design philosophy in Pascal, that it looked at both the right and left hand sides of an expression when deciding what format/precision to use for an operation.

That is not correct. Expressions assignment targets do not influence the evaluation of the expression.

The reason that

Float_Var = 1/3;

evaluates to 0 in C/C++ is that the / operator is overloaded. It can mean either integer division or floating point division. If one of the arguments is floating point then the operator is floating point division, otherwise, as here, it is integer division.

In Delphi the / operator is not overloaded. It is always floating point division. That's why this code gives a compile error:

Int_Var := 1/3;



回答2:


If by "both sides" you mean that it looks at the type of the target variable in an assignment for determining the expression type, then no, that has never been the case. Delphi works like any other mainstream compiler in that regard - that is, the type of an expression is determined from the inside out.



来源:https://stackoverflow.com/questions/15400622/multiplying-longints-expression-of-the-form-int64var-longintvar-longintva

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!