delphi - 为什么编译器会跳过分配变量

标签 delphi delphi-7

我有以下程序:

procedure GetDegree(const num : DWORD ; var degree : DWORD ; min ,sec : Extended);
begin
  degree := num div (500*60*60);
  min := num div (500*60) - degree *60;
  sec := num/500 - min *60 - degree *60*60;
end;

分配 Degree 变量后,调试器跳到过程末尾。这是为什么?

最佳答案

这是一个优化。变量 minsec 按值传递。这意味着对它们的修改不会被调用者看到,并且是该过程私有(private)的。因此,编译器可以认为给它们赋值是没有意义的。分配给变量的值永远无法读取。因此编译器选择节省时间并跳过赋值。 我希望您打算像这样声明该过程:

procedure GetDegree(const num: DWORD; var degree: DWORD; var min, sec: Extended);

正如我在上一个问题中所说,使用扩展并没有多大意义。您最好使用标准浮点类型之一,SingleDouble。或者甚至使用映射到 Double 的通用 Real

此外,您已将 min 声明为浮点类型,但计算结果为整数。在这方面我对你之前问题的回答非常准确。

<小时/>

我建议您创建一条记录来保存这些值。传递三个单独的变量会使您的函数接口(interface)非常困惑并破坏封装。这三个值只有作为一个整体考虑时才有意义。

type
  TGlobalCoordinate = record
    Degrees: Integer;
    Minutes: Integer;
    Seconds: Real;
  end;

function LongLatToGlobalCoordinate(const LongLat: DWORD): TGlobalCoordinate;
begin
  Result.Degrees := LongLat div (500*60*60);
  Result.Minutes := LongLat div (500*60) - Result.Degrees*60;
  Result.Seconds := LongLat/500 - Result.Minutes*60 - Result.Degrees*60*60;
end;

function GlobalCoordinateToLongLat(const Coord: TGlobalCoordinate): DWORD;
begin
  Result := Round(500*(Coord.Seconds + Coord.Minutes*60 + Coord.Degrees*60*60));
end;

关于delphi - 为什么编译器会跳过分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10726052/

相关文章:

delphi - 试图通过单击按钮使Editbox上下移动

delphi - 为什么 EM_SETTEXTMODE 不起作用?

sql-server - 如何从 Delphi 中执行包含许多 GO 语句的大型 SQL 脚本?

forms - Delphi:使窗口可从组件拖动

delphi - 无法读取 Windows 7 64 位上逻辑驱动器的最后几 Kb

database - 如何将数据库值传入和传出代码。在德尔福 7

delphi - 从组合框中更新 TEdit 文本

mysql - 为从 Delphi 到 MySQL 的 ADO 连接指定源 IP

delphi - 如何录制声音并延迟播放?

Delphi 脚本和 ASM