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

仅限制函数的输出指针参数能否充分发挥restrict的作用?

问题:仅为输出指针添加restrict,能否让函数内所有读取操作获得优化收益?

假设我有一个函数,接收若干指针参数:部分非const指针用于写入,部分const指针仅用于读取,示例代码如下:

void f(int * a, int const *b);

同时该函数不会通过其他方式写入内存(即不使用全局变量、固定地址、将const指针强制转换为非const指针等手段)。

按照C语言标准,若仅为输出参数添加restrict限定符(即示例中的a,而非b),是否足以让函数f()内的所有读取操作获得restrict带来的优化收益?

测试验证

通过测试发现这种写法似乎可行,测试代码如下:

int f(int * restrict a, int const * b) {
    a[0] += b[0];
    return a[0] + b[0];
}

int all_restricted(int * restrict a, int const * restrict b) {
    a[0] += b[0];
    return a[0] + b[0];
}

int unrestricted(int * a, int const * b) {
    a[0] += b[0];
    return a[0] + b[0];
}

生成的x86_64目标代码中,f与all_restricted的代码完全一致,而unrestricted的代码不同:

f:
        mov     eax, DWORD PTR [rsi]
        mov     edx, DWORD PTR [rdi]
        add     edx, eax
        mov     DWORD PTR [rdi], edx
        add     eax, edx
        ret
all_restricted:
        mov     eax, DWORD PTR [rsi]
        mov     edx, DWORD PTR [rdi]
        add     edx, eax
        mov     DWORD PTR [rdi], edx
        add     eax, edx
        ret
unrestricted:
        mov     eax, DWORD PTR [rsi]
        add     eax, DWORD PTR [rdi]
        mov     DWORD PTR [rdi], eax
        add     eax, DWORD PTR [rsi]
        ret

不过需要注意,这个测试结果并不构成通用保证。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:57:19