Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is the restrict qualifier in C?

Hammad Nasir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The restrict type qualifier

The restrict type qualifier was introduced in C language after the C99 standard. The restrict type qualifier allows the programmer to declare restricted pointers - pointers that have exclusive access over a memory region. Restricted pointers allow the compiler to optimize the program’s memory access.

The structure of the restrict type qualifier is as follows:

data_type restrict identifier

Note: Accessing the memory location of a restricted pointer using another pointer results in an undefined behavior.

Usage of the restrict type qualifier

The primary usage of the restrict qualifier is in function arguments. The following function foo takes in 3 integer pointers (a, b, and c) and adds the value of c to values of a and b:

Note: The word value here refers to the value at the memory location pointed by the pointers a, b or c.

void foo(int * a, int * b, int * c) {
  *a += *c;
  *b += *c;
}

The function above can be written using the restrict type qualifier as well:

void foo(int * restrict a, int * restrict b, int * restrict c) {
  *a += *c;
  *b += *c;
}

The assembly code in this case is optimized to not reload the value at the memory address at c after the line *a += *c; is executed. Thus, one less instruction is required in the assembly code, and since executable code is one-to-one mapped with assembly code, there will also be one less instruction in the executable code.

RELATED TAGS

c

CONTRIBUTOR

Hammad Nasir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring