• c语言 宏


    #代表命令要被预处理器处理
    #define 定义的宏可以出现在程序的任意位置
    #define 定义之后的代码都可以使用这个宏

    宏是字面量,不占用内存

    单步编译预处理器,只进行文本替换,不进行语法检查:
    gcc -E test.c -D test.i

    完整编译:
    gcc test.c

    宏表达式
    #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=3 
    int s2 = _SUM_(a, b) * _SUM_(a, b); //a+b*a+b =5 
    int m = _MIN_(a++, b); //((a++)<(b)?(a++):(b)) =2 
    int d = _DIM_(c); //sizeof(c)/sizeof(*c) 
    
    // printf("s1 = %d
    ", s1);
    // printf("s2 = %d
    ", s2);
    // printf("m = %d
    ", m);
    // printf("d = %d
    ", d);
    return 0;
    }

    宏的作用域
    宏没有作用域限制,因为是由预处理器处理的

    内置宏
    __FILE__ 被编译的文件名
    __LINE__ 当前行号
    __DATE__ 编译时的日期
    __TIME__ 编译时的时间
    __STDC__ 编译器是否遵循标准c规范

    code:

    #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);
    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;
    }
  • 相关阅读:
    视频分帧
    windows开启ssh服务
    使用geopy计算经纬度表示的坐标之间的距离
    哔站视频下载
    后缀树(Suffix Tree)
    [回滚莫队] AtCoder 歴史の研究
    [长链剖分优化dp] Codeforces 1499F
    [长链剖分优化dp] BZOJ 3522/4543 Hotel
    长链剖分O(nlogn)-O(1)求K级祖先
    [数论] Codeforces 1499D The Number of Pairs
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10994967.html
Copyright © 2020-2023  润新知