Explain volatile and restrict type qualifiers in C with an example


Type qualifiers add special attributes to existing data types in C programming language.

There are three type qualifiers in C language and volatile and restrict type qualifiers are explained below −

Volatile

A volatile type qualifier is used to tell the compiler that a variable is shared. That is, a variable may be referenced and changed by other programs (or) entities if it is declared as volatile.

For example, volatile int x;

Restrict

This is used only with pointers. It indicates that the pointer is only an initial way to access the deference data. It provides more help to the compiler for optimization.

Example Program

Following is the C program for volatile type qualifier −

   int *ptr
   int a= 0;
   ptr = &a;
   ____
   ____
   ____
      *ptr+=4; // Cannot be replaced with *ptr+=9
   ____
   ____
   ____
      *ptr+=5;

Here, the compiler cannot replace the two statements *ptr+=4 and *ptr+=5 by one statement *ptr+=9. Because, it is not clear if the variable ‘a’ can be accessed directly (or) through other pointers.

For example,

   restrict int *ptr
   int a= 0;
   ptr = &a;
   ____
   ____
   ____
      *ptr+=4; // Can be replaced with *ptr+=9
   ____
   ____
      *ptr+=5;
____
   ____

Here, the compiler can replace the two statements by one statement, *ptr+=9. Because, it is sure that variable cannot be accessed through any other resources.

Example

Following is the C program for the use of restrict keyword −

 Live Demo

#include<stdio.h>
void keyword(int* a, int* b, int* restrict c){
   *a += *c;
   // Since c is restrict, compiler will
   // not reload value at address c in
   // its assembly code.
   *b += *c;
}
int main(void){
   int p = 10, q = 20,r=30;
   keyword(&p, &q,&r);
   printf("%d %d %d", p, q,r);
   return 0;
}

Output

When the above program is executed, it produces the following result −

40 50 30

Updated on: 08-Mar-2021

767 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements