You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FPC中for循环结束后迭代变量值不符合预期的技术问询

FPC 3.2.3(Lazarus 4.0 RC1)中For循环变量行为异常问题

在使用FPC 3.2.3(搭配Lazarus 4.0 RC1)时,发现for循环的变量处理不符合预期。

测试代码

procedure TMainForm.ButtonClick(Sender:TObject);
var i:integer;
begin
  for i:=0 to 10 do Log(IntToStr(i));
  Log('@end:'+IntToStr(i));
end;

输出结果

(compiler optimization level 0):   0 1 2 3 4 5 6 7 8 9 10 @end:10
(compiler optimization level 1):   0 1 2 3 4 5 6 7 8 9 10 @end:10
(compiler optimization level 2):   0 1 2 3 4 5 6 7 8 9 10 @end:10
+ compiler warning @line 449: Locale variable "i" does not seem to be initialized
(compiler optimization level 3):   0 1 2 3 4 5 6 7 8 9 10 @end:0
+ compiler warning @line 449: Locale variable "i" does not seem to be initialized

预期与疑问

我预期循环结束后第二次日志输出的i值为11(和C语言行为一致),请问其他Lazarus版本是否能复现该问题?

补充说明

  • 编译器会发出变量未初始化警告,但i作为函数局部变量,作用域覆盖整个函数,且for循环已将其初始化为0。
  • 与C语言不同,Pascal中该变量的作用域并非仅局限于循环体。
  • 编译器允许进行优化,但必须保证结果一致性,当前不同优化级别下输出结果存在差异,这不符合预期。

中断循环的示例

在依赖全局变量中断循环的场景中,无论优化级别如何,i的最终值都应被保留:

var a_global:boolean;

procedure TMainForm.ButtonClick(Sender:TObject);
var i:integer;
begin
  for i:=0 to 10 do begin
    if a_global=true then break;
    Log(IntToStr(i));
  end;
  Log('@end:'+IntToStr(i));
end;

内容的提问来源于stack exchange,提问作者Hannes Brockmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 07:03:14