C++宏定义详解
发布时间:2026-09-25 | 浏览:1
#define <宏名> <字符串>
例: #define PI 3.1415926
#define <宏名> (<参数表>) <宏体>
例: #define A(x) x
例1 #define N 2+2
printf(“%d”,a);
#define N (2+2)
/*这样就可替换成(2+2)*(2+2)=16*/
#define area(x) x*x
/*这在使用中是很容易出现问题的,看如下的程序*/
int y = area(2+2);
printf(“%d”,y);
#include <iostream.h>
#define product(x) x*x
j = product(i++);
cout<<"j="<<j<<endl;
cout<<"i="<<i<<endl;
k = product(++i);
cout<<"k="<<k<<endl;
cout<<"i="<<i<<endl;
#define Conn(x,y) x##y
#define ToChar(x) #@x
#define ToString(x) #x
int n = Conn(123,456); /* 结果就是n=123456;*/
char* str = Conn("asdf", "adf"); /*结果就是 str = "asdfadf";*/
#ifndef BODYDEF_H
#define BODYDEF_H
#define MEM_B( x ) ( *( (byte *) (x) ) )
#define MEM_W( x ) ( *( (word *) (x) ) )
#include <iostream>
#include <windows.h>
#define MEM_B(x) (*((byte*)(x)))
#define MEM_W(x) (*((WORD*)(x)))
int bTest = 0x123456;
byte m = MEM_B((&bTest));/*m=0x56*/
int n = MEM_W((&bTest));/*n=0x3456*/
#define OFFSETOF ( type, field ) ( (size_t) &(( type *) 0)-> field )
#define FSIZ( type, field ) sizeof( ((type *) 0)->field )
#define B_PTR( var ) ( (byte *) (void *) &(var) )
#define W_PTR( var ) ( (word *) (void *) &(var) )
#define UPCASE( c ) ( ((c) >= ''a'' && (c) <= ''z'') ? ((c) - 0x20) : (c) )
#define DECCHK( c ) ((c) >= ''0'' && (c) <= ''9'')
#define HEXCHK( c ) ( ((c) >= ''0'' && (c) <= ''9'') ||((c) >= ''A'' && (c) <= ''F'') ||((c) >= ''a'' && (c) <= ''f'') )
#define INC_SAT( val ) (val = ((val)+1 > (val)) ? (val)+1 : (val))
#define ARR_SIZE( a ) ( sizeof( (a) ) / sizeof( (a[0]) ) )
_LINE_ /*(两个下划线),对应%d*/
_FILE_ /*对应%s*/
_DATE_ /*对应%s*/
_TIME_ /*对应%s*/