zoukankan      html  css  js  c++  java
  • 【转】C语言中的restrict关键字

    '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: 

    [code]
      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);
    [/code]

    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: 


    [code]
      FILE *fopen(const char * filename, const char * mode);
    [/code]

    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: 


      
      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: 

    [code]
      int printf(const char * restrict format, ...);
      char *strcpy(char * restrict s1, const char * restrict s2);
    [/code]

    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. 


    作者:beanmoon
    出处:http://www.cnblogs.com/beanmoon/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
    该文章也同时发布在我的独立博客中-豆月博客

  • 相关阅读:
    Delphi 实现C语言函数调用
    Delphi采用接口实现DLL调用
    select、poll、epoll之间的区别总结[整理]
    int 的重载
    qt 安装包生成2
    线程池的简单实现
    qt 安装包生成
    linux 下tftpf搭建
    2018C语言助教总结
    动态规划——最长子序列长度
  • 原文地址:https://www.cnblogs.com/beanmoon/p/2713365.html
Copyright © 2011-2022 走看看