Mastering C Language: The Importance of Well-Defined Macros

Using macros can prevent errors, enhance portability, readability, and convenience.

Below are some commonly used macros in mature software.

Redefining some types to prevent differences in type byte sizes due to various platforms and compilers, facilitating 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 */

Finding the maximum and minimum values:

#define MAX( x, y ) ( ((x) > (y)) ? (x) : (y) )#define MIN( x, y ) ( ((x) < (y)) ? (x) : (y) )

Getting the offset of a field in a structure (struct):

#define FPOS( type, field ) /*lint -e545 */ ( (dword) &(( type *) 0)-> field ) /*lint +e545 */

Getting the number of bytes occupied by a field in a structure:

#define FSIZ( type, field ) sizeof( ((type *) 0)->field )

Converting two bytes into a Word in LSB format:

#define FLIPW( ray ) ( (((word) (ray)[0]) * 256) + (ray)[1] )

Converting a Word into two bytes in LSB format:

#define FLOPW( ray, val ) (ray)[0] = ((val) / 256); (ray)[1] = ((val) & 0xFF)

Getting the address of a variable (word width):

#define B_PTR( var ) ( (byte *) (void *) &(var) )#define W_PTR( var ) ( (word *) (void *) &(var) )

Getting the high and low byte of a word:

#define WORD_LO(xxx) ((byte) ((word)(xxx) & 255))#define WORD_HI(xxx) ((byte) ((word)(xxx) >> 8))

Converting a letter to uppercase:

#define UPCASE( c ) ( ((c) >= 'a' && (c) <= 'z') ? ((c) - 0x20) : (c) )

Checking if a character is a decimal digit:

#define DECCHK( c ) ((c) >= '0' && (c) <= '9')

Checking if a character is a hexadecimal digit:

#define HEXCHK( c ) ( ((c) >= '0' && (c) <= '9') || ((c) >= 'A' && (c) <= 'F') || ((c) >= 'a' && (c) <= 'f') )

Preventing a header file from being included multiple times:

#ifndef COMDEF_H#define COMDEF_H// Header file content#endif

A method to prevent overflow:

#define INC_SAT( val ) (val = ((val)+1 > (val)) ? (val)+1 : (val))

Returning the number of elements in an array:

Mastering C Language: The Importance of Well-Defined Macros

#define ARR_SIZE( a ) ( sizeof( (a) ) / sizeof( (a[0]) ) )

Leave a Comment