使用已在当前范围内受到限制的受限参数调用函数

标签 c c99 restrict-qualifier

我无法理解 restrict 对于调用具有已受限变量的函数的含义。

Wikipedia告诉我:

The restrict keyword is a declaration of intent given by the programmer to the compiler. It says that for the lifetime of the pointer, only it or a value directly derived from it (such as pointer + 1) will be used to access the object to which it points.

我有这三个示例函数:

void a(int const *p1, int const *p2) {
    ...
}

void b(int *restrict p1, int *restrict p2) {
    ...
}

void c(int *p1, int *p2) {
    ...
}

我会从一个函数中调用它们

foo(int *restrict p1, int *restrict p2) {
    a(p1, p2);
    b(p1, p2);
    c(p1, p1+1);
}

他们中的哪一个会遵守函数 foo 声明所做出的 restrict promise ?

这三种情况是:

  1. 函数a不会修改任何内容,因此这肯定成立。

  2. b 怎么样,它的参数是从 foo 的指针“直接派生”的吗?如果我修改 b 中的 p1p2 ,我是否会违背在 foo 声明中做出的 promise ?

  3. 如果参数不受任何方式限制,并且我在 c 中编辑 p2,则 c 中的情况与之前的情况相比是否会发生变化?

最佳答案

以下是您做出的 promise :

void foo(int *restrict p1, int *restrict p2) {
    // a() can't modify p1[...] or p2[...]
    a(p1, p2);
    // b() CAN modify p1[...] or p2[...]
    // Note that you are still making this promise if you don't use
    // "restrict" in the declaration of b()
    b(p1, p2);
    // c() CAN modify p1[...] but not p2[...]
    c(p1, p1+1);
}

除非您知道这些函数的作用以及它们的调用方式,否则您无法确定您所做的 promise 是否正确。

例如,这是错误的:

int global;
void a(int const *p1, int const *p2) {
    // Since p1 == &global, we can break the promise here
    // by accessing *p1 through the name "global"...
    // Even though this function is perfectly okay by itself!
    global = 5;
}
void foo(int *restrict p1, int *restrict p2) {
    // We have a promise that a() won't modify p1[...]
    // BECAUSE: "restrict" promises that all p1 modifications
    // go through p1, since p1 is passed "const" a() is not
    // supposed to modify *p1, but p1 = &global, and a() modifies
    // global... BOOM!
    // Even though this function is perfectly okay by itself...
    a(p1, p2);
}
int main() {
    int y;
    // Illegal!  Once you pass &global to foo(), BOOM!
    foo(&global, &y);
}

这就是为什么restrict有点棘手。仅根据函数签名无法判断它是否正确。

关于使用已在当前范围内受到限制的受限参数调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28530162/

相关文章:

c - 以编程方式检测 3gb 开关是否打开或关闭

c程序客户端服务器

c - 在 if 语句中使用 strcmp

c - 有人为 MSP430 的 IAR Embedded Workbench 实现了 __getzone() 吗?

c - Makefile - 对函数的 undefined reference

c - 结构中 restrict 关键字的行为

c - 如何使用Axis2c从WSDL文件生成C文件

c - 是否正在积极开发下一个 C 标准?

c++ - 具有限制指针的 OpenMP 因 ICC 而失败,而 GCC/G++ 成功

C++ 限制语义