Home  >  Article  >  Backend Development  >  Explain volatile and restrict type qualifiers in C language, with an example

Explain volatile and restrict type qualifiers in C language, with an example

王林
王林forward
2023-09-10 22:25:01789browse

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

Explain volatile and restrict type qualifiers in C language, with an example

There are three type qualifiers in the C language, among which volatile and restricted type qualifiers are explained as follows-

Volatile

A Yi Losing type qualifiers are used to tell the compiler that variables are shared. That is, if a variable is declared volatile, it can be referenced and changed by other programs (or) entities.

For example, volatile int x;

Restrictions

This only works with pointers. It shows that pointers are only the initial way of accessing referenced data. It provides more help for compiler optimization.

Sample program

The following is a 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 use a statement *ptr =9 to Replace the two statements *ptr =4 and *ptr =5. Because, it is not clear whether 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 two statements with one statement, *ptr =9. Because, for sure, the variable cannot be accessed through any other resource.

Example

The following is a C program using the restrict keyword-

Live demonstration

#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 , will produce the following results-

40 50 30

The above is the detailed content of Explain volatile and restrict type qualifiers in C language, with an example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete