#define的一个小技巧

时间:2022-07-24
本文章向大家介绍#define的一个小技巧,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
/* atof example: sine calculator */
#include <stdio.h>      /* printf, fgets */
#include <stdlib.h>     /* atof */
#include <math.h>       /* sin */



#define vfd_com_timeout_clear()     do{vfd_com_cnt = 0;}while(0)
#define vfd_com_timeout_recount()   do{vfd_com_cnt = 0;}while(0)

/*
判断等待时间是否超时
*/
int is_eload_com_timeout(void)
{
    //电子负载超过2s时间尚未反馈
    if (1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}


int main ()
{
    double n, m;
    double pi = 3.1415926535;
    char buffer[256] = {"000000.01212n234"};

    int vfd_com_cnt = 5;
    printf("vfd_com_cnt = %dn",vfd_com_cnt);
    vfd_com_timeout_clear();
    printf("vfd_com_cnt = %dn",vfd_com_cnt);

    if (!is_eload_com_timeout())
    {
		printf("oooon");
    }
	else
	{
		printf("kkkkkn");
	}
	

    n = atof (buffer);
    printf("n=%fn", n);
    m = sin (n * pi / 180);
    printf ("The sine of %f degrees is %fn", n, m);
    return 0;
}

int is_eload_com_timeout(void)
{

    if (1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}


int main ()
{
    double n, m;
    double pi = 3.1415926535;
    char buffer[256] = {"000000.01212n234"};

    int vfd_com_cnt = 5;
    printf("vfd_com_cnt = %dn",vfd_com_cnt);
    do{vfd_com_cnt = 0;}while(0);
    printf("vfd_com_cnt = %dn",vfd_com_cnt);

    if (!is_eload_com_timeout())
    {
  printf("oooon");
    }
 else
 {
  printf("kkkkkn");
 }


    n = atof (buffer);
    printf("n=%fn", n);
    m = sin (n * pi / 180);
    printf ("The sine of %f degrees is %fn", n, m);
    return 0;
}

上文已经就将源代码和预编译后的比分文字合作一起了。

#define vfd_com_timeout_clear() do{vfd_com_cnt = 0;}while(0)

这个代码我起初以为会有问题,应为括号里面是空的,

但是使用gcc -E .atofc.c -o atofc.i后,发现直接替换了,因此该方法可以使用。

但是注意,宏定义不检查语法的,因此写宏定义的时候要格外小心。