C 的 restrict关键字

等级 5383 次按键

定义使用 restrict 指针的 copyArray:向编译器保证 dest 和 src 不会指向重叠的内存,使其能够优化循环。它把源数组的每个值乘 2 写入目标数组,打印 Source: 1 2 3 4 5 和 Dest: 2 4 6 8 10。

C 代码

// restrict 保证 dest 和 src 不重叠,因此每次写入后无需重新读取值
// const 使 src 在函数内只读
1void copyArray(int * restrict dest, const int * restrict src, int n) {
// 逐个处理这 n 个元素
2 for (int i = 0; i < n; i++) {
// 写入源值的两倍;编译器可以假定这不会改变 src
3 dest[i] = src[i] * 2;
4 }
5}
6
// 输入值
7int source[] = {1, 2, 3, 4, 5};
// 用于存放结果的独立数组,因此满足 restrict 的保证
8int destination[5];
9
// 向 destination 填入 2、4、6、8、10
10copyArray(destination, source, 5);
11
// 打印“Source: 1 2 3 4 5”;src 未被修改
12printf("Source: ");
13for (int i = 0; i < 5; i++) printf("%d ", source[i]);
// 换行后打印“Dest: 2 4 6 8 10”
14printf("\nDest: ");
15for (int i = 0; i < 5; i++) printf("%d ", destination[i]);
// 用换行结束输出行
16printf("\n");

运行结果

Source: 1 2 3 4 5 
Dest: 2 4 6 8 10
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C 代码中需要输入的符号及其出现次数。

  • ;× 15
  • ,× 10
  • "× 10
  • (× 10
  • )× 10
  • [× 6
  • ]× 6
  • +× 6
  • =× 5
  • {× 3

C 等级 5 的更多代码示例

← 返回 C 打字练习