# Define usage highlights

Source: Internet
Author: User
Tags constant definition

Definition:

The # define Directive

You can use the # define directive to give a meaningful name to a constant in your program. The two forms of the syntax are:

Syntax

# Define identifier token-stringopt

# Define identifier [(identifieropt,..., identifieropt)] token-stringopt

 

Usage:

 

1.SimpleDefineDefinition

# Define maxtime1000

A simple maxtime is defined. It represents 1000. If you write

If (I <maxtime ){.........}

The compiler replaces maxtime with 1000 before processing this code.

This definition looks similar to a normal constant definition const, but it is also different, because the definition of define is more like a simple text replacement, rather than being used as a volume, this problem is particularly highlighted below.

2. DefineOf"Function Definition"

Define can accept some parameters as the function does, as follows:

# Define max (x, y) (x)> (y )? (X) :( y );

This definition will return the big one in two numbers. Have you seen it? Because this "function" does not have a type check, it is like a function template. Of course, it is definitely not as secure as a template. It can be used as a simple template.

But there are hidden risks in doing so, for example: # define add (A, B) A + B; it is normal in general use, but if you encounter: C * Add (a, B) * D is problematic. The purpose of the algebraic formula is to multiply A + B with C and D, however, because define is used (it is just a simple replacement), the formula is actually changed to C * A + B * D.

Another example is: # define pin (int *); pin a, B; the intention is that both A and B are int-type pointers, but they are actually int * a, B; A is an int pointer while B is an int variable. This should use typedef instead of define, so that both A and B are int type pointers.

Therefore, when defining it, we should develop a good habit. We recommend that you add brackets to all layers.

3.Single Row definition of macros (rarely seen)

# Define a (x) T _ # X # define B (X) # @ X # define C (x) # x

Suppose: x = 1, there are:

A (1) ------> T_1 B (1) ------> '1' C (1) ------> "1"

(For more information, see hustli)

3. DefineMulti-line definition

Define can replace multiple lines of code, such as the macro definition in MFC (very classic, although disgusting)

# Define macro (arg1, arg2) do {\/* declarations */\ stmt1; \ stmt2 ;\/*... */\} while (0)/* (no trailing;) */The key is to add "\" to each line feed "\"

4.In large-scale development, especially cross-platform and system software,DefineThe most important feature is Conditional compilation.

That is: # ifdef windows...

You can use # define to set the compiling environment during compilation.

5.How to define and cancel macros

// Define macro # define [macroname] [macrovalue] // cancel macro # UNDEF [macroname] // normal macro # define Pi (3.1415926)

Macro with parameters # define max (A, B) (a)> (B )? (A), (B) the key is that errors are easily generated, including differences in machine and human understanding.

6.Conditional compilation# Ifdef XXX... (# Else )... # Endif example # ifdef dv22_aux_input # define aux_mode 3 # else # define auy_mode 3 # endif # ifndef XXX... (# Else )... # Endif

7.Header file(. H)Header files orCFile Inclusion;Repeated inclusion (repeated definition) because the header file can be nested, the C file may contain the same header file multiple times, and the problem of repeated definition may occur. Use the Conditional compilation switch to avoid repeated inclusion (repeated definition), for example, # ifndef _ headerfilexxx _ # DEFINE _ headerfilexxx __... // File content... # Endif

 

 

Instances:

 

1To prevent a header file from being repeatedly contained

# Ifndef comdef_h

# Define comdef_h

// Header file content

# Endif

2And redefines some types to prevent the differences in the number of bytes of the type caused by different platforms and compilers, so as to facilitate migration.

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 */

// The following is not recommended

Typedef unsigned char byte;/* unsigned 8 bit value type .*/

Typedef unsigned short word;/* unsinged 16 bit value type .*/

Typedef unsigned long DWORD;/* unsigned 32 bit value type .*/

Typedef unsigned char uint1;/* unsigned 8 bit value type .*/

Typedef unsigned short uint2;/* unsigned 16 bit value type .*/

Typedef unsigned long uint4;/* unsigned 32 bit value type .*/

Typedef signed Char int1;/* signed 8 bit value type .*/

Typedef signed short int2;/* signed 16 bit value type .*/

Typedef long int int4;/* signed 32 bit value type .*/

Typedef signed long sint31;/* signed 32 bit value */

Typedef signed short sint15;/* signed 16 bit value */

Typedef signed Char sint7;/* signed 8 bit value */

3To obtain a byte or word on the specified address.

# Define mem_ B (x) (* (byte *) (x )))

# Define mem_w (x) (* (word *) (X )))

4, Calculate the maximum and minimum values

# Define max (x, y) (x)> (y ))? (X): (y ))

# Define min (x, y) (x) <(y ))? (X): (y ))

5, GetFieldIn struct(Struct)Offset in

# Define FPOs (type, field )\

/* Lint-e545 */(DWORD) & (type *) 0)-> Field)/* lint + e545 */

6To obtain a structFieldNumber of bytes occupied

# Define fsiz (type, field) sizeof (type *) 0)-> field)

7, AccordingLSBFormat to convert two bytes into oneWord

# Define flipw (Ray) (Word) (Ray) [0]) * 256) + (Ray) [1])

8, AccordingLSBFormatWordConvert to two bytes

# Define flopw (Ray, Val )\

(Ray) [0] = (VAL)/256 );\

(Ray) [1] = (VAL) & 0xff)

9To get the address of a variable (WordWidth)

# Define B _ptr (VAR) (byte *) (void *) & (VAR ))

# Define w_ptr (VAR) (word *) (void *) & (VAR ))

10To obtain the high and low bytes of a word.

# Define word_lo (XXX) (byte) (Word) (XXX) & 255 ))

# Define word_hi (XXX) (byte) (Word) (XXX)> 8 ))

11, Returns a ratioXThe largest closest8Multiples

# Define rnd8 (x) + 7)/8) * 8)

12Converts a letter to uppercase.

# Define upcase (C) (c)> = 'A' & (c) <= 'Z ')? (C)-0x20): (c ))

13, Judge whether the character is10Number of the input value

# Define decchk (C) (c)> = '0' & (c) <= '9 ')

14, Judge whether the character is16Number of the input value

# Define hexchk (C) (c)> = '0' & (c) <= '9') | \

(C)> = 'A' & (c) <= 'F') | \

(C)> = 'A' & (c) <= 'F '))

15To prevent overflow.

# Define inc_sat (VAL) (val = (VAL) + 1> (VAL ))? (VAL) + 1: (VAL ))

16, Returns the number of array elements

# Define arr_size (A) (sizeof (a)/sizeof (A [0])

17Returns an unsigned number.NEnd valueMod_by_power_of_two (x, n) = x % (2 ^ N)

# Define mod_by_power_of_two (Val, mod_by )\

(DWORD) (VAL) & (DWORD) (mod_by)-1 ))

18ForIoSpace ing in the bucket structure, Input/Output Processing

# Define Indium (port) (* (volatile byte *) (port )))

# Define inpw (port) (* (volatile word *) (port )))

# Define inpdw (port) (* (volatile DWORD *) (port )))

# Define outp (port, Val) (* (volatile byte *) (port) = (byte) (VAL )))

# Define outpw (port, Val) (* (volatile word *) (port) = (Word) (VAL )))

# Define outpdw (port, Val) (* (volatile DWORD *) (port) = (DWORD) (VAL )))

19, Use some macro tracking debugging

The ANSI standard specifies five predefined macro names. They are:

_ Line __

_ File __

_ Date __

_ Time __

_ Stdc __

C ++ also defines _ cplusplus

If the compiler is not standard, only a few of the above macro names are supported or not supported at all. Remember that the Compilation Program may also provide other predefined macro names.

_ Line _ and _ file _ macro instructions. # The line command can change its value. In short, during compilation, it contains the current number of lines and file names of the program.

The _ date _ macro command contains a string in the form of month, day, or year, which indicates the date when the source file was translated to the code.

The _ time _ macro command contains the program Compilation Time. Time is represented by a string in the form of minute: Second

The significance of the _ stdc _ macro command is defined during compilation. Generally, if _ stdc _ has been defined, the compiler will only accept standard C/C ++ code that does not contain any non-standard extensions. If the implementation is standard, macro _ stdc _ contains the decimal constant 1. If it contains any other number, the implementation is non-standard.

The consistent compiler of _ cplusplus and Standard C ++ defines it as a value containing at least six characters. A compiler that is inconsistent with the standard C ++ will use a value of 5 or less.

You can define macros, for example:

When _ debug is defined, the output data and the row of the file

# Ifdef _ debug

# Define debugmsg (MSG, date) printf (MSG); printf ("% d", date, _ line _, _ file _)

# Else

# Define debugmsg (MSG, date)

# Endif

 

20Macro definition to prevent incorrect use of parentheses.

For example:

Definition in question: # define dump_write (ADDR, NR) {memcpy (bufp, ADDR, NR); bufp + = nR ;}

Definition: # difne do (a, B) do {A + B; A ++;} while (0)

For example:

If (ADDR)

Dump_write (ADDR, NR );

Else

Do_somethong_else ();

This will happen after the macro scale:

If (ADDR)

{Memcpy (bufp, ADDR, NR); bufp + = nR ;};

Else

Do_something_else ();

When GCC encounters the ";" in front of Else, it considers that the if statement has ended, so the subsequent else is not in the IF statement. With the do {} while (0) definition, there is no problem under any circumstances. The definition of # difne do (a, B) do {A + B; A ++;} while (0) will not go wrong under any circumstances.

 

21. DefineSpecial identifier in

# Define conn (x, y) x # y # define tochar (x) # @ X # define tostring (x) # x

Int A = conn (12, 34); char B = tochar (a); char C [] = tostring (a); the result is a = 1234, c = 'A ', C = '000000 ';

It can be seen that # Is a simple connector, # @ is used to add single quotation marks to parameters, # is used to add double quotation marks to parameters to convert them into strings

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.