Restrict Keyword In C

In most cases, the restrict keyword is primarily employed to specify pointer declaration as a type of qualifier for the pointers. Despite not introducing any novel functionalities or features, its purpose is clear. By utilizing this keyword, programmers can prompt the compiler to optimize wherever possible.

In simpler terms, when the "restrict" keyword is applied to a pointer like ptr, it indicates to the compiler that ptr is the sole means of accessing the object it points to. This instruction does not prompt the compiler to insert extra validations. Essentially, no other pointer should reference the same object. Nevertheless, if a user disregards this directive, unpredictable outcomes or erratic program behavior may occur.

Note: C++ does not support the restrict keyword, and it's only a keyword of the C programming language.

To gain a deeper comprehension of the "restrict" keywords, we can examine the provided examples below, showcasing the straightforward application of these keywords.

Example 1

Example

#include <stdio.h>
/* In this function we are adding the value of variable c to other variables a and y */
void function(int* a, int* b, int* restrict c) 
{
  *a += *c;  
/* Updating value of variable a by adding the value of variables a and c */
  *b += *c;  
/* Updating value of variable b by adding the value of variables b and c. Since c is restrict, compiler will not reload value at address c in its assembly code. Therefore generated assembly code will be optimized */
}
int main(void) 
{
  int a = 50 , b = 100 , c = 150 ;
  function(&a, &b, &c);
  printf("%d %d %d", a, b, c);
}

Output

Output

200 250 150

Example 2

Example

#include <stdio.h>
void my_function(int* x, int* y, int* restrict z) {
   *x += *z;
   *y += *z;
}
main(void) {
   int x = 10, y = 20, z = 30;
   my_function(&x, &y, &z);
   printf("%d %d %d", x, y, z);
}

Output

Output

40 50 30

Q1. Where can you use a restrict keyword?

A . To a pointer

Syntax:

Example

int* restrict p;

Q2. If you include the 'restrict' keyword with the pointer, the compiler will assume that the pointer is the only means to access the data it points to.

A. It is expected that the memory referenced by 'p' will be exclusively accessed by 'p' only.

Q3. How does the compiler's optimization help?

A. Typically, data referenced by a pointer can be altered by any other pointer. Normally, when you perform an operation that includes reading a pointer, you must reload the stored value in the pointer (the value being pointed to) into the CPU register. However, if it's confirmed that there is only a single pointer, in certain situations, you can omit the reloading process.

Conclusion

In this guide, we have detailed the "restrict" keyword in C programming, striving to maintain simplicity throughout. Furthermore, we have addressed common inquiries typically associated with the "restrict" keyword.

Input Required

This code uses input(). Please provide values below: