학습자료(~2017)/팁

__restrict__

단세포소년 2012. 7. 26. 11:17
반응형

사전적 의미 : 
1. (크기・양・범위 등을) 제한하다
2. (자유로운 움직임을) 방해하다
3. (규칙・법으로) 제한하다


C 언어에서 의미 : 
restrict 키워드는 오직 포인터에만 적용되는 키워드로 그 포인터가 데이터 객체에 접근할수 있는 유일하고도 최초가 되는 수단임을 나타낸다. 즉 포인터가 restrict로 한정되면 그 포인터가 가리키는 데이터 블록은 그 포인터만이 접근이 가능하다.(같은 SCOPE(쉽게 생각하면 '{' '}' 블럭 안) 상에서)


예를 들어 

strcpy() 함수는 

char * strcpy (char *restrict to, const char *restrict from) 형태를 갖는다.

이것은 strcpy 함수 내에서는 to와 from 이 가르키는 데이터블럭은 자기자신만 접근가능하다는 소리이다.

즉. to 와 from 은 같은 주소가 될수 없다는 말을 명시적으로 해준것이다.


참고 : http://msdn.microsoft.com/ko-kr/library/5ft82fed.aspx

참고 :

'Restrict' Pointers

One of the new features in the recently approved C standard C99, is the restrict pointer qualifier. This qualifier can be applied to a data pointer to indicate that, during the scope of that pointer declaration, all data accessed through it will be accessed only through that pointer but not through any other pointer. The 'restrict' keyword thus enables the compiler to perform certain optimizations based on the premise that a given object cannot be changed through another pointer. Now you're probably asking yourself, "doesn't const already guarantee that?" No, it doesn't. The qualifier const ensures that a variable cannot be changed through a particular pointer. However, it's still possible to change the variable through a different pointer. For example:

 

  void f (const int* pci, int *pi;); // is *pci immutable?
  {
    (*pi)+=1; // not necessarily: n is incremented by 1
     *pi = (*pci) + 2; // n is incremented by 2
  }
  int n;
  f( &n, &n);
 

In this example, both pci and pi point to the same variable, n. You can't change n's value through pci but you can change it using pi. Therefore, the compiler isn't allowed to optimize memory access for *pci by preloading n's value. In this example, the compiler indeed shouldn't preload n because its value changes three times during the execution of f(). However, there are situations in which a variable is accessed only through a single pointer. For example:

 

  FILE *fopen(const char * filename, const char * mode);

The name of the file and its open mode are accessed through unique pointers in fopen(). Therefore, it's possible to preload the values to which the pointers are bound. Indeed, the C99 standard revised the prototype of the function fopen() to the following:

 
  /* new declaration of fopen() in <stdio.h> */
  FILE *fopen(const char * restrict filename, 
                        const char * restrict mode);

Similar changes were applied to the entire standard C library: printf(), strcpy() and many other functions now take restrict pointers:

 
  int printf(const char * restrict format, ...);
  char *strcpy(char * restrict s1, const char * restrict s2);

C++ doesn't support restrict yet. However, since many C++ compilers are also C compilers, it's likely that this feature will be added to most C++ compilers too


반응형