Common methods and skills of C Language

Source: Internet
Author: User

Common methods and skills of C Language

Common C language methods and techniques

Big end and Small End Selection

Low-endian or high-endian

typedef union {short W;/* Word access */struct {/* Byte access */#ifdef LOW_ENDIANbyte low, high;/* in low-endian arch */#elsebyte high, low;/* in high-endian arch */#endif} B;} word;
Remainder operation
A = a % 8; => a = a & 7; Note: bitwise operations only require one instruction cycle. a subroutine is usually called to obtain the remainder.
Square operation
A = pow (a, 2.0); => a = a * a; note: In the processor of the built-in multiplication operator, multiplication is faster than square calculation. Even if there is no built-in multiplication operator, the subprograms of multiplication operations are also more efficient than the subprograms of square operations.
Shift to realize multiplication and division
A = a * 4; B = B/4; => a = a <2; B = B> 2; note: multiply by or divide by 2n, you can use the shift method instead. A = a * 9; => a = (a <3) +;
While loop and do... while loop
Note: do... the code generated after the while LOOP compilation is shorter than the while loop.
Type redefinition, extended portability
typedef unsigned char       boolean; /* Boolean value type. */typedef unsigned long int   uint32; /* Unsigned 32 bit value */typedef unsigned short      uint16; /* Unsigned 16 bit value */typedef unsigned char       uint8; /* Unsigned 8 bit value */typedef signed long int     int32; /* Signed 32 bit value */typedef signed short        int16; /* Signed 16 bit value */typedef signed char         int8; /* Signed 8 bit value */
Obtains a byte or word on the specified address.
typedef unsigned char   byte; /* Unsigned 8 bit value type */ typedef unsigned short  word; /* Unsigned 16 bit value type */#define MEM_B(x)    (*((byte*)(x)))#define MEM_W(x)    (*((word*)(x)))
Obtain extreme values
#define MAX(x, y)   ((x) > (y) ? (x) : (y))#define MIN(x, y)   ((x) < (y) ? (x) : (y))
Obtains the offset of a field in the struct.
typedef unsigned long   dword; /* Unsigned 32 bit value type */#define FPOS(type, field)\    ( (dword)&((type*)0)->field )
Obtains the number of bytes occupied by the field in a struct.
#define FSIZE(type, field)\    ( sizeof(((type*)0)->field) )
Convert a word (16 bit) into two bytes in LSB format
#define FLOPW(ray, val)\    do {\        (ray)[0] = ((val)>>8);\        (ray)[1] = ((val)&0xFF);\    }while(0);
Get the address of a Variable
typedef unsigned char   byte; /* Unsigned 8 bit value type */typedef unsigned short  word; /* Unsigned 16 bit value type */  #define B_PTR(var)  ((byte*)(void*)&(var))#define W_PTR(var)  ((word*)(void*)&(var))
Obtains the low and high bits of a byte.
typedef unsigned char   byte; /* Unsigned 8 bit value type */typedef unsigned short  word; /* Unsigned 16 bit value type */#define WORD_L(var) ((byte)(word)(var)&(0xFF))#define WORD_H(var) ((byte)(word)(var)>>(8))
Returns a multiple of nearly 8 greater than X.
#define RND8(x) ((((x) + 7) >> 3) << 3) 
Methods To prevent overflow
#define INC_SAT(val)\    ((val) = ( ((val) + 1) > (val)) ? ((val) + 1):(val) )
Returns the number of array elements.
#define ARR_SIZE(a)\    ( (sizeof(a)) / (sizeof(a[0])) )
Returns the last n digits of an unsigned number.
typedef unsigned long   dword; /* Unsigned 32 bit value type */ #define MOD_BY_POWER_OF_TWO(val, mod_by)\    ((dword)(val)&(dword)(2<<(mod_by) - 1))
Structure of IO space ing in the bucket
typedef unsigned char   byte;   /* Unsigned 8 bit value type */typedef unsigned short  word;   /* Unsigned 16 bit value type */typedef unsigned long   dword;  /* Unsigned 32 bit value type */#define outp(port)      (*((volatile byte *)(port)))#define outpw(port)     (*((volatile word *)(port)))#define outpdw(port)    (*((volatile dword *)(port)))#define inp(port, val)      (*((volatile byte *)(port)))    = (byte)(val)#define inpw(port, val)     (*((volatile word *)(port)))    = (word)(val)#define inpdw(port, val)    (*((volatile dword *)(port)))   = (dword)(val)
Usage of "#" and "#" in macro
1. Use "#" to convert macro parameters into a string, and use "#" to combine the two macro parameters. # Define STR (val) (# val) # define CONS (a, B) (int) (a ## e ## B)-> STR (hello) ==> "hello" CONS (2, 3) ==> 2000 // 2e3 2. When the macro parameter is another macro, it should be noted that the remote macro parameter '#' or '#' in the macro definition will not expand. 1. Non-'#' and '# define TOW (2) # define MUL (a, B) (a * B) printf ("% d * % d = % d \ n", TOW, TOW, MUL (TOW, TOW )); ==> printf ("% d * % d = % d \ n", (2), (2), (2) * (2 ))); the TOW parameter in MUL is expanded to (2 ). 2. When '#' or '#' is available, # define A (2) # define STR (s) # s # define CONS (a, B) int (a # e # B) printf ("int max: % s \ n", STR (INT_MAX )); // INT_MAX # include ==> printf ("int max: % s \ n", "INT_MAX"); printf ("% s \ n", CONS (, a); // compile error => printf ("% s \ n", int (AeA); INT_MAX and A will not be expanded, however, the method to solve this problem is very simple. adding another layer of intermediate conversion macro means to expand all macro parameters in this layer, then the macro (_ STR) in the conversion macro can get the correct macro parameter. # define A (2) # define _ STR (s) (# s) # define STR (s) _ STR (s) // convert macro # define _ CONS (, b) int (a # e # B) # define CONS (a, B) _ CONS (a, B) // convert the macro printf ("int max: % s \ n ", STR (INT_MAX); // The maximum value of INT_MAX, int type, is a variable # include output: int max: 0x7fffffff STR (INT_MAX) --> _ STR (0x7fffffff) and then convert it to A string; printf ("% d \ n", CONS (A, A); output: 200 CONS (A,) --> _ CONS (2), (2) --> int (2) e (2 )) iii. Application Cases of '#' and '#' 1. Merge anonymous variable names # define ___ ANONYMOUS1 (type, var, line) type var # line # define _ ANONYMOUS0 (type, line) ___ ANONYMOUS1 (type, _ anonymous, line) # define ANONYMOUS (type) _ ANONYMOUS0 (type, _ LINE _) Example: ANONYMOUS (static int); that is, static int _ anonymous70; 70 indicates the row number; Level 1: ANONYMOUS (static int ); --> _ ANONYMOUS0 (static int, _ LINE _); Layer 2: --> ___ ANONYMOUS1 (static int, _ anonymous, 70); Layer 3: --> static int _ anonymous70; that is, only macros of the current layer can be unlocked at each time. Therefore, _ LINE _ can be unlocked at the second layer. 2. FILL in the structure # define FILL () {a, # a} enum IDD {OPEN, CLOSE}; typedef struct MSG {IDD id; const char * msg;} MSG; MSG _ msg [] = {FILL (OPEN), FILL (CLOSE) };=> MSG _ msg [] ={{ OPEN, "OPEN"}, {CLOSE, "CLOSE" }}; 3. Record File name # define _ GET_FILE_NAME (f) # f # define GET_FILE_NAME (f) _ GET_FILE_NAME (f) static char FILE_NAME [] = GET_FILE_NAME (_ FILE _); 4. Obtain the buffer size of the string corresponding to the value type # define _ TYPE_BUF_SIZE (type) sizeof # type # define TYPE_BUF_SIZE (type) _ TYPE_BUF_SIZE (type) char buf [TYPE_BUF_SIZE (INT_MAX)]; --> char buf [_ TYPE_BUF_SIZE (0x7fffffff)]; --> char buf [sizeof "0x7fffffff"]; equivalent to: char buf [11];

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.