The difference between #define, const, typedef

Source: Internet
Author: User
Tags define definition


The difference between #define, const, typedef


#define is not defining variables, it's just for text substitution.
For example:
#define PI 3.1415926
float Angel;
angel=30*pi/180;

Then, when the program is compiled, the compiler will first "#define PI 3.1415926" after the "PI" in all the code is replaced by "3.1415926"

and then compile.

I found a post that says the difference between Const and # define, where the biggest difference between const and # define is that the former allocates space on the stack, while the latter simply passes the specific value directly to the target variable. Or, the const constant is a run-time concept, and he really exists in the program and can be called and passed. The # define constant is a compile-time concept whose life cycle ends at compile time: in the actual program he is only a constant, a parameter in a command, there is no actual existence.

Const constants exist in the data segment of the program, #define常量存在于程序的代码段.

As for the pros and cons of both, it depends on the specific situation. General constant application, I personally think that # define is a better choice:

I. From a run-time point of view, he has a good advantage in both space and time.

Ii. from a compile-time point of view, code similar to m=t*10 is not optimized by the compiler, T*10 operations need to be performed in Run-time. The constants for # define will be merged (in the example above t*10 will be replaced by 0x82).

However: if you need to change the value of a constant in a rude manner, you have to use const, because the latter does not actually exist in the program. (In fact, it should be said that modifying the data segment is simpler than the code snippet ^_^).


Definition:
The #define Directive
You can use the #define directive to give a meaningful name to a constant in your program. The forms of the syntax are:
Syntax
#define Identifier Token-stringopt
#define Identifier[(identifieropt, ..., identifieropt)] Token-stringopt


1. Simple define Definition
#define MAXTIME 1000

"Function definition" of 2.define
Define can accept some parameters like a function, as follows
#define MAX (x, y) > (y)? (x):(y);
Because this "function" does not have a type check, it is like a function template, no template is so safe.
But there are pitfalls to doing so, examples are:
#define ADD (b) a+b, if you encounter a problem such as: c * ADD (b) * d.
Also give an example:
#define PIN (int*);
Pin A, B;
The original intention is that A and B are both int type pointers, but actually become int* a, B;
A is an int pointer, and b is a variable of type int.
You should use typedef instead of define so that both A and B are int pointers.
When we define it, we develop a good habit and suggest that all levels be bracketed.

3. Single-line definition of macros (uncommon usage)
#define A (x) t_# #x
#define B (x) #@x
#define C (x) #x
We assume that: X=1, there are:
A (1)------〉t_1
B (1)------' 1 '
C (1)------"1"

Multi-line definition for 4.define
Define can replace multiple lines of code, such as the macro definition in MFC (very classic, although it makes people look disgusting)
#define MACRO (arg1, arg2) do {\
/* declarations */\
STMT1; \
STMT2; \
/* ... */ \
} while (0)/* (no trailing;) */
The key is to add a "\" to each line break

5. In the large-scale development process, especially in cross-platform and system software, the most important function of define is conditional compilation.
It is:
#ifdef WINDOWS
......
......
#endif
#ifdef LINUX
......
......
#endif
You can set up the compilation environment by # define at compile time.

6. How to define macros, cancel macros
#define [MacroName] [macrovalue]//define Macros
#undef [MacroName]//Cancel macro
#define PI (3.1415926)//Normal macro
#define MAX (a) > (b)? (a), (b))//macro with Parameters

7. Conditional compilation
#ifdef XXX ... (#else) ... #endif
For example
#ifdef Dv22_aux_input
#define AUX_MODE 3
#else
#define AUY_MODE 3
#endif
#ifndef XXX ... (#else) ... #endif

8. Prevent a header file from being repeatedly included
Because the header file contains can be nested, then the C file may contain the same header file multiple times, there may be a duplicate definition of the problem.
Avoid duplicate inclusions with conditional compilation switches (duplicate definitions)
For example
#ifndef __headerfilexxx__
#define __headerfilexxx__
...
File contents
...
#endif




Instances:
1. Prevent a header file from being repeatedly included
#ifndef Comdef_h
#define Comdef_h
Header file Contents
#endif
When you build a project with multiple source files, it is possible to include the same header file in multiple files, if borrowing the macro definition above can prevent the same head file from being repeatedly included in the compilation. Because a # define COMDEF_H is always not defined when it compiles the first header file, it compiles all the contents of the header file, including defining the # define COMDEF_H. If you encounter the same header file that you want to compile as you compile and then go down, it will not compile the header file again because of the presence of the statement #ifndef Comdef_h.
2. Redefine some types to prevent differences in the number of types of bytes produced due to different platforms and compilers, facilitating portability.
typedef unsigned char Boolean; /* Boolean value type. */
typedef unsigned long int uint32; /* Unsigned-bit value */
typedef unsigned short uint16; /* Unsigned-bit value */
typedef unsigned char uint8; /* Unsigned 8 bit value */
typedef signed Long int int32; /* Signed-bit value */
typedef signed short Int16; /* Signed-bit value */
typedef signed CHAR int8; /* Signed 8 bit value */
The following is not recommended for use
typedef unsigned char byte; /* Unsigned 8 bit value type. */
typedef unsigned short word; /* unsinged-bit value type. */
typedef unsigned long DWORD; /* Unsigned-bit value type. */
typedef unsigned char uint1; /* Unsigned 8 bit value type. */
typedef unsigned short Uint2; /* Unsigned-bit value type. */
typedef unsigned long uint4; /* Unsigned-bit value type. */
typedef signed Char Int1; /* Signed 8 bit value type. */
typedef signed short Int2; /* Signed-bit value type. */
typedef long int int4; /* Signed-bit value type. */
typedef signed Long SINT31; /* Signed-bit value */
typedef signed short sint15; /* Signed-bit value */
typedef signed Char SINT7; /* Signed 8 bit value */

3. Get a byte or a word on the specified address
#define MEM_B (x) (* (BYTE *) (x))
#define MEM_W (x) (* ((Word *) (x)))

4. Find the maximum and minimum values
#define MAX (x, Y) (((x) > (y))? (x): (y))
#define MIN (x, Y) (((x) < (y))? (x): (y))

5. Get the offset of a field in the struct (struct)
#define FPOS (Type, field) & ((type *) 0), field)

6. Get the number of bytes occupied by field in a struct
#define FSIZ (type, field) sizeof (((type *) 0)->field)

7. Convert two bytes to one word in LSB format
#define FLIPW (Ray) (((Word) (Ray) [0]) + (Ray) [1])

8. Convert a word to two bytes in LSB format
#define FLOPW (Ray, Val) \
(Ray) [0] = ((val)/256); \
(Ray) [1] = ((val) & 0xFF)

9. Get the address of a variable (word width)
#define B_PTR (Var) ((BYTE *) (void *) & (Var))
#define W_PTR (Var) ((Word *) (void *) & (Var))

10. Get 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 multiple of the nearest 8 that is larger than X
#define RND8 (x) (((((x) + 7)/8) * 8)

12. Convert one letter to uppercase
#define UPCASE (c) (((c) >= ' A ' && (c) <= ' Z ')? ((c)-0x20): (c))

13. Determine if a character is a number that is 10 in value
#define DECCHK (c) ((c) >= ' 0 ' && (c) <= ' 9 ')

14. Determine if a character is a number that is 16 in value
#define HEXCHK (c) (((c) >= ' 0 ' && (c) <= ' 9 ') | | \
((c) >= ' A ' && (c) <= ' F ') | | \
((c) >= ' A ' && (c) <= ' F '))

15. One way to 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))) <!--[if!supportannotations]-->[lst1]<!--[endif]-->

17. Returns the value of an unsigned N-tailed Mod_by_power_of_two (X,n) =x% (2^n)
#define Mod_by_power_of_two (val, mod_by) \
((DWORD) (VAL) & (DWORD) ((mod_by)-1))

18. For IO space mapping in the storage space structure, the input and output processing
#define INP (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 describes five predefined macro names. They are:
__line__
__file__
__date__
__time__
__stdc__
__cplusplus is also defined in C + +.
If the compiler is not standard, it is possible to support only a few of the macro names above, or not at all. Remember that the compiler may also provide other predefined macro names.
__LINE__ and __FILE__ macros indicate that, #line指令可以改变它的值, simply speaking, when compiled, they contain the current number of lines and file names of the program.
The __DATE__ macro directive contains a string of months/days/years, indicating the date when the source file was translated to the code.
The __TIME__ macro directive contains the time that the program was compiled. Time is represented by a string, in the form: minutes: seconds
The meaning of the __STDC__ macro directive is defined at compile time. In general, if __STDC__ is already defined, the compiler will only accept standard C + + code that does not contain any non-standard extensions. If the implementation is standard, the macro __stdc__ contains a decimal constant of 1. If it contains any other number, the implementation is non-standard.
__cplusplus A compiler that is consistent with standard C + + defines it as a value that contains at least 6. Compilers that are inconsistent with standard C + + will use a numeric value that has 5 bits or less.
You can define macros, for example:
When the _DEBUG is defined, the output data information and the file where the
#ifdef _DEBUG
#define DEBUGMSG (msg,date) printf (msg);p rintf ("%d%d%d", Date,_line_,_file_)
#else
#define DEBUGMSG (Msg,date)
#endif

20. Macro definitions prevent errors from being included with parentheses.
For example:
Problematic definition: #define Dump_write (ADDR,NR) {memcpy (BUFP,ADDR,NR); BUFP + = nr;}
Definitions that should be used: #difne do (A, b) do{a+b;a++;} while (0)
For example:
if (addr)
Dump_write (ADDR,NR);
Else
Do_somethong_else ();
After the macro expands, it becomes this:
if (addr)
{memcpy (BUFP,ADDR,NR); BUFP + = nr;};
Else
Do_something_else ();
GCC considers that the IF statement has ended when it encounters the ";" in front of else, so that the later else is not in the IF statement. With the definition of do{} while (0), there is no problem in any case. Instead #define DO (A, b) do{a+b;a++;} while (0) is defined without error in any case
Special identifiers in define
#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,b= ' a ', c= "a";
You can see that # # is a simple connector,
#@ used to convert arguments to single characters (the last character)
#用来给参数加双引号即转成字符串




Usage and differentiation of typedef and # define
I. Usage of typedef
A typedef is commonly used to define an identifier and an alias for a keyword in the C + + language, which is part of the language compilation process, but it does not actually allocate memory space, such as:
typedef int INT;
typedef int ARRAY[10];
typedef (INT*) PINT;
typedef can enhance the readability of the program, as well as the flexibility of identifiers, but it also has a "non-intuitive" and other shortcomings.
Second, #define的用法
#define为一宏定义语句, it is commonly used to define constants (including parametric and parametric), and to implement macros that are "seemingly benign, behind a long string", which is not itself in the process of compiling, but before (the pre-processing process) is completed. However, it is also difficult to identify potential errors and other code maintenance problems, and its examples are as follows:
#define INT int
#define TRUE 1
#define ADD (b) ((a) + (b));
#define LOOP_10 for (int i=0; i<10; i++)
In article 1 of effective C + + of Scott Meyer, there is an analysis of the drawbacks of the # define statement, as well as a good alternative, as you can see.
Three, the difference between typedef and # define
From the above concepts can also be basically clear, TypeDef is only to increase the readability of the identifier for the new name (just an alias), and # define was originally in C in order to define constants, to the C++,const, enum, The advent of inline makes it a tool for aliases as well. Sometimes it is easy to figure out with the typedef which is the best, such as the # define int int Such statements, with a typedef can be done, with which good? I contend with TypeDef, because this statement is illegal in many of the earlier C compilers, but today's compilers are expanded. To be as compatible as possible, it is common to follow a # define definition of "readable" constants and the tasks of some macro statements, whereas a typedef is often used to define keywords, lengthy types of aliases.
A macro definition is simply a string substitution (in-place extension), whereas a typedef is not an in-place extension, and its new name has a certain encapsulation so that the newly named identifier has the ability to define variables more easily. Take a look at the third line of the first big point of the code above:
typedef (INT*) PINT;
and the following line:
#define PINT2 int*
Same effect? It's different! See the difference in practice: PINT A, B, the effect with int *a; An int *b that defines two integer pointer variables. And pINT2 A, B; the effect is the same as int *a;
Indicates that an integer pointer variable A and integer variable B are defined.





The difference between #define, const, typedef

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.