用示例解釋C語言中的volatile和restrict型別限定符


型別限定符在C程式語言中為現有資料型別新增特殊屬性。

C語言中有三個型別限定符,下面解釋volatile和restrict型別限定符:

Volatile

volatile型別限定符用於告訴編譯器變數是共享的。也就是說,如果一個變數被宣告為volatile,它可能被其他程式(或)實體引用和更改。

例如,volatile int x;

Restrict

這僅與指標一起使用。它表明指標只是訪問解引用資料的初始方式。它為編譯器最佳化提供了更多幫助。

示例程式

以下是volatile型別限定符的C程式:

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

在這裡,編譯器不能將語句*ptr+=4和*ptr+=5替換為一個語句*ptr+=9。因為,不清楚變數'a'能否直接訪問(或)透過其他指標訪問。

例如:

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

在這裡,編譯器可以將兩個語句替換為一個語句*ptr+=9。因為它確定變數無法透過任何其他資源訪問。

示例

以下是使用restrict關鍵字的C程式:

 線上演示

#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;
}

輸出

執行上述程式時,會產生以下結果:

40 50 30

更新於:2021年3月8日

854 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.