C宏不完全展开的情况

遇到了一个宏没有完全展开的情况。

#include <stdlib.h>
#include <stdio.h>

/* Use printf inside the definition */
#define PRINTF(fmt, args...)    do { printf(fmt, ##args); } while (0)

/* Make printf represent as the encapsulated print */
#define printf PRINTF

int main(int argc, char* *argv) {
    int p = 100;
    printf("p = %d\n", *p);
    return EXIT_SUCCESS;
}

 在PRINTF里用到了printf这个名字。然后想又用printf作为标准名称,实际指向经过封装的PRINTF。

结果会出现PRINTF函数未定义的情况。

分析原因应该是

     1. 宏展开时预处理器遇到printf按最近的解释执行。发现可以用PRINTF,(第一层展开)

     2. 但是准备展开PRINTF时发现PRINTF的定义包含printf,如果允许执行第二层展开。则按照这个允许的逻辑必须执行第三层展开 。如此会构成死循环,所以中止。(第二层展开中止)

改动最里层的宏定义后,可以正常执行展开。

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>

int printf2(char const *fmt, ...) {
    int n = 0;
    va_list args;
    va_start(args, fmt);
    n = vprintf(fmt, args);
    va_end(args);
    return n;
}

/* Use printf inside the definition */
#define PRINTF(fmt, args...)    do { printf2(fmt, ##args); } while (0)

/* Make printf represent as the encapsulated print */
#define printf PRINTF

int main(int argc, char* *argv) {
    int p = 100;
    printf("p = %d\n", p);
    return EXIT_SUCCESS;
}

猜你喜欢

转载自chenqi210.iteye.com/blog/2381797