1、#运算符
#运算符用于在预处理期将宏参数转换为字符串
#的转换作用是在预处理期完成的,因此只在宏定义中有效
编译器不知道#的转换作用
用法 :
#define STRING(x) #x
printf("%s\n", STRING(Hello World!));
2、实例分析
#运算符的基本用法 25-1.c
#include <stdio.h>
#define STRING(x) #x
int main()
{
printf("%s\n", STRING(Hello world!));
printf("%s\n", STRING(100));
printf("%s\n", STRING(while));
printf("%s\n", STRING(return));
return 0;
}
test.i
3、实例分析
#运算符的妙用 25-2.c
#include <stdio.h>
#define CALL(f, p) (printf("Call function %s\n", #f), f(p))
int square(int n)
{
return n * n;
}
int func(int x)
{
return x;
}
int main()
{
int result = 0;
result = CALL(square, 4);
printf("result = %d\n", result);
result = CALL(func, 10);
printf("result = %d\n", result);
return 0;
}
test.i
只有通过这种方式获得变量名
4、##运算符
##运算符用于在预处理期粘连两个标识符
##的连接作用是在预处理期完成的,因此只在宏定义中有效
编译器不知道##的连接作用
用法 :
#define CONNECT(a, b) a##b
int CONNECT(a, 1); // int a1;
a1= 2;
5、实例分析
##运算符的基本用法 25-3.c
#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\n", NAME(1));
printf("%d\n", NAME(2));
return 0;
}
test.i
6、实例分析
##运算符的工程应用 25-4.c
#include <stdio.h>
#define STRUCT(type) typedef struct _tag_##type type;\
struct _tag_##type
STRUCT(Student)
{
char* name;
int id;
};
int main()
{
Student s1;
Student s2;
s1.name = "s1";
s1.id = 0;
s2.name = "s2";
s2.id = 1;
printf("s1.name = %s\n", s1.name);
printf("s1.id = %d\n", s1.id);
printf("s2.name = %s\n", s2.name);
printf("s2.id = %d\n", s2.id);
return 0;
}
7、实例分析
#include <Windows.h>
int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hPreInstance, PSTR szCmdLine, int iCmdHow)
{
MessageBox(NULL, TEXT("Hi"), TEXT("hello"), MB_OK);
return 0;
}
Windows编程常用TEXT解决编码问题
#define TEXT(quote) __TEXT(quote) // r_winnt
#define __TEXT(quote) L##quote // r_winnt
8、小结
#运算符用于在预处理期将宏参数转换为字符串
##运算符用于在预处理期粘连两个标识符
编译器不知道#和##运算符的存在
#和##运算符只在宏定义中有效