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
相关产品推荐
相关产品推荐

