zoukankan      html  css  js  c++  java
  • 第十六章:C预处理器

    1.宏(macro)

    1.1定义宏

    #define macro body
    
    example:
    #define PI 3.14 //object-like macro
    #define SQUARE(x) ((x)*(x)) //function-like macro

    1.2预处理器不进行计算,而只进行字符串替换。比如,对于x*x用x+2替换x则会得到x+2*x+2.

    1.3#运算符

    如果x是一个宏参量,那么#x可以把参数名转化为相应字符串。该过程称为字符串化(stringizing)。

    #include <stdio.h>
    #define PSQR(x) printf("The square of " #x " is %d.
    ",((x)*(x)))
    int main(void)
    {
        int y = 5;
        PSQR(y);
        PSQR(2 + 4);
        return 0;
    }
    
    Here’s the output:
    The square of y is 25.
    The square of 2 + 4 is 36.

    1.4##运算符

    这个运算符可以把两个token组合成单个token。

    #define XNAME(n) x ## n
    
    Then the macro
    XNAME(4)
    
    would expand to the following:
    x4

    1.5Here are some points to note:

    Remember that there are no spaces in the macro name, but that spaces can appear in the replacement string. ANSI C permits spaces in the argument list.

    Use parentheses around each argument and around the definition as a whole. This ensures that the enclosed terms are grouped properly in an expression such as forks = 2 * MAX(guests + 3, last);

    Use capital letters for macro function names. This convention is not as widespread as that of using capitals for macro constants. However, one good reason for using capitals is to remind yourself to be alert to possible macro side effects.

    ■ If you intend to use a macro instead of a function primarily to speed up a program, first try to determine whether it is likely to make a significant difference. A macro that is used once in a program probably won’t make any noticeable improvement in running time. A macro inside a nested loop is a much better candidate for speed improvements. Many systems offer program profilers to help you pin down where a program spends the most time.

  • 相关阅读:
    时间复杂度 空间复杂度
    qt 打开串口 UI卡死
    python 网络编程
    Java 理解泛型的基本含义
    Java LinkedList 和 ArrayList
    Java renameTo()重新命名此抽象路径名表示的文件
    Java separatorChar 如何在Java里面添加
    Java 遍历文件夹里面的全部文件、指定文件
    Java File文件操作 创建文件目录,删除文件目录
    Java toString()方法的神奇之处
  • 原文地址:https://www.cnblogs.com/bukekangli/p/4311803.html
Copyright © 2011-2022 走看看