现在的位置: 首页 > 综合 > 正文

C语言宏

2018年01月11日 ⁄ 综合 ⁄ 共 1647字 ⁄ 字号 评论关闭

1.常量

#include <stdio.h>
#include <stdlib.h>

#define PI_PLUS_ONE (3.14 + 1)

int main(int argc, char *argv[])
{
    float x = PI_PLUS_ONE * 5;

    printf("x = %f\n",x);

    return 0;
}

输出结果:

x = 20.700001

2.条件编译:#if, #elif, #else, #ifdef, #ifndef. 

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
#if 0
    printf("if 0\n");
#elif 0
    printf("elif\n");
#else
    printf("else\n");
#endif
    return 0;
}

3.防止重包含

#ifndef _FILE_NAME_H_
#define _FILE_NAME_H_

/* code */

#endif // #ifndef _FILE_NAME_H_

4.防止宏重定义

#ifndef NULL
#define NULL (void *)0
#endif // #ifndef NULL

5.宏函数

#define MULT(x, y) (x) * (y)
#define SWAP(a, b)  a ^= b; b ^= a; a ^= b; 

看如下代码是否合理?

#include <stdio.h>
#include <stdlib.h>

#define SWAP(a, b)  { a ^= b; b ^= a; a ^= b; }

int main(int argc, char *argv[])
{
    int x = 10; 
    int y = 5;
    int z = 4;

    if(x < 0)
        SWAP(x, y); 
    else
        SWAP(x, z); 
    printf("x = %d,y = %d,z = %d\n",x,y,z);

    return 0;
}

但编译这段代码的时候,会报如下错误:
gcc  -c -Wall -O0 -g -I/home/sunke/include main.c
main.c: In function ‘main’:
main.c:15: error: ‘else’ without a previous ‘if’
make: *** [main.o] Error 1
这里有一个技巧写这个宏可以规避这个问题:

#include <stdio.h>
#include <stdlib.h>

#define SWAP(a, b)  do{ a ^= b; b ^= a; a ^= b; }while(0)

int main(int argc, char *argv[])
{
    int x = 10; 
    int y = 5;
    int z = 4;

    if(x < 0)
        SWAP(x, y); 
    else
        SWAP(x, z); 
    printf("x = %d,y = %d,z = %d\n",x,y,z);

    return 0;
}

多行宏:

#define SWAP(a, b)  {                   \
                        a ^= b;         \
                        b ^= a;         \ 
                        a ^= b;         \
                    } 

6.高级技巧

#include <stdio.h>
#include <stdlib.h>

#define PRINT_TOKEN(token) printf(#token " is %d", token)

int main(int argc,char **argv)
{
    char *foo = "foo";
    PRINT_TOKEN(foo);

    return 0;
}

输出结果:
foo is 134513936

7.双#使用

#include <stdio.h>
#include <stdlib.h>

void quit_command();
void help_command();

struct command
{
    char * name;
    void (*function) (void);
};

#define COMMAND(NAME) { #NAME, NAME ## _command }

struct command commands[] = { 
    COMMAND(quit),
    COMMAND(help),
};

void quit_command()
{
    printf("quit command\n");
}
void help_command()
{
    printf("help command\n");
}

抱歉!评论已关闭.