 View Code
View Code 
#include <stdio.h> #define MAX(x,y) (x>y?x:y) #define PRINT_INT(x) printf(#x" %d\n",x) #define PRINT_F(x) printf(#x" %f\n",x) #define PRINT_HELLO() \ printf("Hello, World\n") #define GENERIC_MAX(type) \ type type##_max(type x,type y) \ { \ return x>y?x:y; \ } \ #define CHECK_ZERO(divisor) \ if (divisor == 0) \ printf("*** Attempt to divide by zero on line %d "\ "of file %s ***\n",__LINE__,__FILE__) int main() { printf("Wacky Windows (c) 1996 Wacky Software, Inc.\n"); printf("Compiled on %s at %s\n", __DATE__,__TIME__); printf("Hello \n"); #ifdef DEBUG printf("Debug...\n"); #endif printf("max: %d\n",MAX(3,4)); int x = 1021; PRINT_INT(x); PRINT_HELLO(); GENERIC_MAX(int); int z = int_max(5,1); GENERIC_MAX(float); float f = float_max(12.3,11.1); PRINT_INT(z); PRINT_F(f); int i = 100, j = 1; CHECK_ZERO(j); int k = i/j; }
 View Code
View Code 
gcc -DDEBUG t.c ./a.out Wacky Windows (c) 1996 Wacky Software, Inc. Compiled on Nov 30 2012 at 11:57:49 Hello Debug... max: 4 x 1021 Hello, World z 5 f 12.300000
注:
宏参数没有类型检查;
无法用一个指针来指向宏;
宏可能会不止一次地计算它的参数,如: MAX(i++,j);
在涉及到运算操作时记得要添加圆括号
#define error_check(rc,str) \ if(rc < 0) { \ fprintf(stderr,"%s: In function '%s' line(%d): %s, %s.\n", \ __FILE__, __FUNCTION__,__LINE__,str,strerror(errno)); \ exit(1); \ } #define set_nonblock(fd) \ {int rc = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); \ error_check(rc,"fcntl: set_nonblock");}
 
                    
                     
                    
                 
                    
                 
 
        
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号