Notes - macro definition with parameters

(1) with reference macro definition, no space occurs between the macro name and a parameter list
(2) in the macro definition passed by value does not exist, it is only a replacement process symbols
(3) with reference macro definition, parameters, not allocate memory space, and therefore do not have to type definitions

#define MAX(a,b) (a>b)?a:b
void main(void)
{
	int x,y,max;
	printf("Plasy input two numbers :");
	scanf("%d %d",&x,&y);
	max=MAX(x,y);
	printf("The max is: %d\n\n",max);
}

(4) the parameter is defined in the macro identifier, macro invocation argument can be an expression

#define SAY(y) (y)  //y可以是一个表达式 
void main()
{
	int i=0;
	char say[]="hello word!";
	while(say[i])
	{
		say[i]=SAY(say[i]);
		i++;
	}
	printf("\n\t%s\n\n",say);
 } 

(5) In macro definitions, parameters typically takes a string enclosed in parentheses, to avoid errors

#define SQ(y) (y)*(y)
//#define SQ(y) y*y      (不带括号)
void main()
{
	int a,sq;
	printf("input a number:");
	scanf("%d",&a);
	sq=SQ(a+1); // sq=(a+1)*(a+1)
    //  sq=SQ(a+1); // sq=a+1*a+1     (不带括号) 
	printf("sq = %d\n",sq);	
} 

So in the programming process should try to avoid using too many macros, because due to the priority there is a logical error prone macro call

(6) macros and functions with arguments with parameters are similar, but are essentially different, except for the above points, with the same expression and function processing result of the processing with the macro there may be different

int SQ(int y);
void main()
{
	int i=1;
	while(i<=5)
	{
		printf("%d\n",SQ(i++));
	}
} 
int SQ(int y)
{
	return ((y)*(y));
}

#define SQ(y) ( (y)*(y) )
void main()
{
	int i=1;
	while(i<=5)
	{
		printf("%d\n",SQ(i++));
	}
}//output: 2 12 30

(7) macros can be used to define a number of statements in the macro call these statements into the source code and substitution

#define STR(s1,s2,s3,sum) strcat(strcat(strcat(sum,s1),s2),s3);
void main()
{
	char str1[]="上帝",str2[]="是",str3[]="笨蛋",str[40]="";
	STR(str1,str2,str3,str)
	printf("\n\tstr1= %s\n\tstr2= %s\n\tstr3= %s\n\tstr= %s\n\n",str1,str2,str3,str);
}

//strcat(str1,str2)函数将字符串str2粘贴到str1的后面
Published 152 original articles · won praise 22 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_38204302/article/details/105176649