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

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

王林
Release: 2023-09-10 22:25:01
forward
813 people have browsed it

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;
Copy after login

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;
____
   ____
Copy after login

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;
}
Copy after login

Output

When the above program is executed , will produce the following results-

40 50 30
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template