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

Pascal中{$I-}指令的作用域:过程返回后是否仍生效?

Pascal中{$I-}编译指令的作用域问题
  • {$I-}不会在过程返回后自动恢复,会保持全局生效,所以必须手动在过程末尾添加{$I+}来恢复默认的I/O检查机制。
  • 原理说明:Pascal里这类编译指令属于全局状态设置,一旦启用就会持续影响后续所有代码逻辑,不管代码是在过程内还是过程外。如果不手动恢复,整个程序后续的所有I/O操作都会关闭自动错误触发,必须依赖IOResult来判断错误,很容易遗漏异常处理,埋下潜在bug。

修正后的代码示例:

procedure RewriteText(
    FileName: string;
    var TextFile: text;
    var ErrMsg: string
);
begin
    {$I-}
    assign(TextFile, FileName);
    rewrite(TextFile);
    if (IOResult <> 0) then
        ErrMsg := 'Error. Couldn''t write to the file';
    {$I+} // 手动恢复I/O检查
end;

更严谨的写法(避免异常导致恢复操作未执行):

如果过程中间可能因异常跳出,建议用try-finally包裹,确保{$I+}一定会执行:

procedure RewriteText(
    FileName: string;
    var TextFile: text;
    var ErrMsg: string
);
begin
    {$I-}
    try
        assign(TextFile, FileName);
        rewrite(TextFile);
        if (IOResult <> 0) then
            ErrMsg := 'Error. Couldn''t write to the file';
    finally
        {$I+} // 无论是否出错都会恢复I/O检查
    end;
end;

内容的提问来源于stack exchange,提问作者Bogdan Doroschenko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 01:39:49