zoukankan      html  css  js  c++  java
  • C语言-第20课

    第20课 - ###运算符使用解析

     

    1. #运算符

    #运算符用于在预编译期将宏参数转换为字符串

    #include <stdio.h>

    #define CONVERS(x) #x

    int main()

    {  

        printf("%s ", CONVERS(Hello world!));

        printf("%s ", CONVERS(100));

        printf("%s ", CONVERS(while));

        printf("%s ", CONVERS(return));

        return 0;

    }

    运算结果:Hello world! 

                     100 

                      while 

                      return

    例子:#运算符在宏中的妙用

    #include <stdio.h>

    #define CALL(f, p) (printf("Call function %s ", #f), f(p))

    int square(int n)

    {

        return n * n;

    }

    int f(int x)

    {

        return x;

    }

    int main()

    {

        

        printf("1. %d ", CALL(square, 4));

        printf("2. %d ", CALL(f, 10));

        return 0;

    }

    运行结果:Call function square

          16

              Call function f

          10

     

     

     

     

    1. ##运算符

    ##运算符用于在预编译期粘连两个符号

    #include <stdio.h>

    #define NAME(n) name##n

    int main()

    {  

        int NAME(1);  //相当于定义了NAME1

        int NAME(2);  //相当于定义了NAME2

        NAME(1) = 1;

        NAME(2) = 2;   

        printf("%d ", NAME(1));

        printf("%d ", NAME(2));

        return 0;

    }

    运行结果:1

                      2

     

    例子:利用##定义结构类型

    #include <stdio.h>

    #define STRUCT(type) typedef struct _tag_##type type;

    struct _tag_##type

    STRUCT(Student)   //将结构体重新定义得到的

    {

        char* name;

        int id;

    };

    //经过预处理得到的会是下面的语句

    /*

    typedef struct _tag_Student Student;struct _tag_Student

    {

        char* name;

        int id;

    };

    */

    int main()

    {  

        Student s1;

        Student s2;

        s1.name = "s1";

        s1.id = 0;   

        s2.name = "s2";

        s2.id = 1;  

        printf("%s ", s1.name);

        printf("%d ", s1.id);

        printf("%s ", s2.name);

        printf("%d ", s2.id);

        return 0;

    }

    宏很强大,有时候是函数所达不到的。

  • 相关阅读:
    eclipse新 java 文件时自动生成注释
    int占几个字节
    eclipse常用插件
    Asp.net中IsPostBack的实现原理
    Github的入门简介
    Hypertable
    VA01/VA02行项目物料搜索帮助新增页签
    rich_text
    js之Math
    js function参数
  • 原文地址:https://www.cnblogs.com/free-1122/p/9720736.html
Copyright © 2011-2022 走看看