编译器比预处理器更有效!

来源:互联网 发布:^ c语言 编辑:程序博客网 时间:2024/05/16 11:12

    预处理器,他的作用就像名字所说.对于代码按照语法进行预处理.比如常用的 #include. #define,其作用只是简单的替换.当然预处理器不只可以这些事,vc编译器提供了大量的预处理指令,提供包括编译命令行,隐式链接等功能.

     看看维基百科对于预处理器的解释吧:

 

       In computer science, a preprocessor is a program that processes its input data to produce output that is used as input to another program. The output is said to be a preprocessed form of the input data, which is often used by some subsequent programs like compilers. The amount and kind of processing done depends on the nature of the preprocessor; some preprocessors are only capable of performing relatively simple textual substitutions and macro expansions, while others have the power of fully-fledged programming languages.

        A common example from computer programming is the processing performed on source code before the next step of compilation. In some computer languages(e.g., C) there is a phase of translation known as preprocessing.

        在计算机技术中,预处理器一个程序,它会根据输入数据产生输出数据.其他程序会用到这些输出数据.这些输出数据被称作是对输入数据的一种预处理,通常像编译器之类的程序会用到这些输出数据.预处理的数量和种类取决于编译器的性质.有些编译器仅仅是做一些相对简单的文本替换和宏展开功能.也有的编译器提供很强大预编译语言.

       一个常见的例子是:在编程中,预处理器会预先处理源代码,之后才会编译.在一些编程语言中(如C),预处理会首先做一些翻译的事情.

     

      其实平常我所使用的预处理器用的最多的功能就是#define ,用它来定义常量,或者错误码.这时候预处理器所做的只是简单的替换功能,最终检查错误的还是编译器.而且#define还有三个明显不如:

      1. 简单替换,增加代码长度;

      2. 由于只是替换,不会在符号表里有任何信息.所以对调试没有任何帮助;

      3. 预处理器不会检查某些语法错误,并且会带来隐含的问题. 如 :

       #define MAX(a,b) ( (a)>(b) ? (a) : (b) )

当这么用时:   MAX( a++, b );

a做加法的次数竟然取决于比较的大小................

  (摘自Effective c++)

解决的方法是利用类型安全的 inline template function

template< typename T >

inline T& Max( const T& a,const T& b )

{

    return a > b ? a : b;

 

既可以获得宏所带来的效率以及一般函数所可预料的行为以及类型安全性....

 

实在是妙不可言.