blogernice

导航

printf中#号的意思

#进行宏字符串连接,在宏中 把参数解释为字符串,不可以在语句中直接使用。

在宏定义中

printf("%s;/n", #S) 会被解释为

printf("%s;/n", "S")

例如下面的代码

code start

#define TRACE(S) (printf("%s;/n", #S), S) /*注意用逗号而不是分号*/


#include <stdio.h>

#include <stdlib.h>

#include <string.h>


int main(){

    int a=5;

    int b=TRACE(a);

    const char *str="hello";

    char des[50];

    strcpy(des,TRACE(str));

    puts(des);

    system("pause");

   return 0;

}

code end

 输出结果为:

a;

str;

hello

同时宏定义又是一个逗号表达式,所以拷贝到des里面的值为后面S也就是str的值。

 

又比如下面的解释:

3 .宏的单行定义(少见用法)

  #define A(x) T_##x

#define B(x) #@x

#define C(x) #x

我们假设:x = 1 ,则有:

A( 1 ) ------ 〉T_1

B( 1 ) ------ 〉 ' 1 '

C( 1 ) ------ 〉 " 1 " 

posted on 2018-10-30 17:49  blogernice  阅读(2064)  评论(0编辑  收藏  举报