Restrict Keyword in C

Level 5383 keystrokes

Defines copyArray with restrict pointers, a promise to the compiler that dest and src never point to overlapping memory, so it can optimize the loop. It writes each source value doubled into the destination and prints Source: 1 2 3 4 5 and Dest: 2 4 6 8 10.

C code

// restrict promises dest and src never overlap, so values need not be reloaded after each write
// const makes src read-only inside the function
1void copyArray(int * restrict dest, const int * restrict src, int n) {
// Processes the n elements one by one
2 for (int i = 0; i < n; i++) {
// Writes twice the source value; the compiler may assume this never changes src
3 dest[i] = src[i] * 2;
4 }
5}
6
// The input values
7int source[] = {1, 2, 3, 4, 5};
// A separate array for the result, so the promise of restrict holds
8int destination[5];
9
// Fills destination with 2, 4, 6, 8, 10
10copyArray(destination, source, 5);
11
// Prints Source: 1 2 3 4 5; src was not modified
12printf("Source: ");
13for (int i = 0; i < 5; i++) printf("%d ", source[i]);
// Starts a new line and prints Dest: 2 4 6 8 10
14printf("\nDest: ");
15for (int i = 0; i < 5; i++) printf("%d ", destination[i]);
// Ends the output line
16printf("\n");

Output

Source: 1 2 3 4 5 
Dest: 2 4 6 8 10
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

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

More C examples at level 5

← C typing practice