# Define usage

Source: Internet
Author: User
Tags define definition

1. Simple define Definition

# Deprecision MAX 1000

A simple max is defined. It represents 1000. If you write
For (I = 0; I {
................
}
The compiler replaces MAX with 1000 before processing this code.

2. define's "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.

However, there are hidden risks. The example is as follows:
# Define Add (a, B) a + B;
In general use, there is no problem, but if you encounter problems such as: c * Add (a, B) * d, the purpose of the algebraic formula is that a + B is then multiplied by c and d, but because define is used (it is just a simple replacement), the formula is actually changed
C * a + B * d

Another example is as follows:
# Define pin (int *);
Pin a, B;
The intention is that a and B are both int-type pointers, but they actually become 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.

3. Single Row definition of macros
# 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. define multi-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 a "," to each line feed without spaces.

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.