• C语言学习笔记--C语言中的宏定义


    1. C 语言中的宏定义

    1#define 预处理器处理的单元实体之一(因此,预处理器只是简单的进行替换,并
    2#define 定义的宏可以出现在程序的任意位置(包括函数体的内部)
    3#define 定义之后的代码都可以使用这个宏

    2. 定义宏常量 

    1#define 定义的宏常量可以直接使用
    2#define 定义的宏常量本质为字面

    3. 宏定义表达式

    1#define 表达式的使用类似函数调用
    2#define 表达式可以比函数更强大
    3#define 表达式比函数更容易出错

    #include <stdio.h>
    #define _SUM_(a, b) (a) + (b)
    #define _MIN_(a, b) ((a) < (b) ? (a) : (b))
    #define _DIM_(a) sizeof(a)/sizeof(*a)
    int main()
    {
        int a = 1;
        int b = 2;
        int c[4] = {0};
        int s1 = _SUM_(a, b); //(a)+(b)
        int s2 = _SUM_(a, b) * _SUM_(a, b); //(a)+(b)*(a)+(b)
        int m = _MIN_(a++, b); //((a++)<(b)?(a++):(b))
        int d = _DIM_(c); //sizeof(c)/sizeof(*c);
        printf("s1 = %d
    ", s1); // 3
        printf("s2 = %d
    ", s2); // 5
        printf("m = %d
    ", m); // 2
        printf("d = %d
    ", d); // 4
        return 0;
    }

    4. 宏表达式与函数的对比

    1)宏表达式被预处理器处理,编译器不知道宏表达式的存在
    2)宏表达式用实参完全替代形参,不进行任何运算

    3)宏表达式没有任何的调用开销

    4)宏表达式中不能出现递归定义
    内置宏

    #include <stdio.h>
    #include <malloc.h>
    #define MALLOC(type, x) (type*)malloc(sizeof(type)*x)
    #define FREE(p) (free(p), p=NULL)
    #define LOG(s) printf("[%s] {%s:%d} %s 
    ", __DATE__, __FILE__,__LINE__, s)
    #define FOREACH(i, m) for(i=0; i<m; i++)
    #define BEGIN {
    #define END }
    int main()
    {
        int x = 0;
        int* p = MALLOC(int, 5); //以 int 类型作为参数!
        LOG("Begin to run main code...");FOREACH(x, 5)
        BEGIN
        p[x] = x;
       END
        FOREACH(x, 5)
        BEGIN
        printf("%d
    ", p[x]);
        END
        FREE(p);
        LOG("End");
        return 0;
    }

    参考资料:
    www.dt4sw.com
    http://www.cnblogs.com/5iedu/category/804081.html

  • 相关阅读:
    SED&AWK
    load average[zhuan]
    To be learned
    Android计时器 android.widget.Chronometer
    Play初识
    获取视图的宽高
    自定义摄像机
    Android VideoView使用小记
    在android中,如何去掉webview读取网页后点击网页上的按钮出现的方框
    阿里云主机试用之自建站点和ftp上传所遇的2个问题
  • 原文地址:https://www.cnblogs.com/CoderTian/p/5903189.html
Copyright © 2020-2023  润新知