[C语言] 预处理

吾生也有涯,而知也无涯。这篇文章主要讲述[C语言] 预处理相关的知识,希望能为你提供帮助。
预处理



定义宏
--定义宏要套两层括号  ((x)+(x))
--#

#define _CRT_SECURE_NO_WARNINGS 1
#include < stdio.h>

#define SQUARE(x) x*x
#define PRINT(X) printf("the value of "#X" is %d\\n",X)
#define CAT(X,Y) X##Y
int main()
{
printf("%d\\n",SQUARE(3)); //3*3
printf("%d\\n",SQUARE(3+1)); // 3+1*3+1

int a = 10;
PRINT(a);
//printf("the value of "a" is %d\\n",X); 三段字符拼成一段
int b = 20;
PRINT(b);
int c = 30;
PRINT(c);

int yyds666 = 10;
printf("%d",CAT(yyds,666)); //字符串拼接

return 0;
}



宏的副作用


#define _CRT_SECURE_NO_WARNINGS 1
#include < stdio.h>
#define MAX(X,Y) ((X)> (Y))?(X):(Y)
int main()
{
int a = 5;
int b = 8;
int m = MAX(a++,b++);
printf("a = %d b = %d\\n",a,b); // a =6 b = 10

printf("m = %d\\n",m); // m = 9



return 0;
}



取消定义



atoi
#define _CRT_SECURE_NO_WARNINGS 1
#include < stdio.h>
#include < assert.h>
#include < limits.h>
#include < ctype.h>

enum State
{
INVALID,
VALID
};

enum State state = INVALID;

int my_atoi(const char* s)
{
int flag = 1;
//空指针
if (NULL == s)
{
return 0;
}
//空字符
if (*s == \\0)
{
return 0;
}
//跳过空白字符
while (isspace(*s))
{
s++;
}
//+ / -
if (*s == +)
{
flag = 1;
s++;
}
else if (*s == -)
{
flag = -1;
s++;
}
//处理数字字符的转换
long long n = 0;
while (isdigit(*s))
{
n = n * 10 + flag * (*s - 0);
if (n > INT_MAX || n < INT_MIN)
{
return 0;
}
s++;
}
if (*s == \\0)
{
state = VALID;
return (int)n;
}
else
{
//非数字字符的情况
return (int)n;
}



}

int main()
{

const char* p = "-1234";
int ret = my_atoi(p);
if(state == VALID)
printf("合法的转换:%d\\n",ret);
else
printf("不合法的转换:%d\\n", ret);

return 0;
}



【[C语言] 预处理】


    推荐阅读