C and C ++ preprocessor of a known type and name (III) with typedef

Ali P7 mobile Internet architect, Advanced Video (Daily update) for free learning, please click: https://space.bilibili.com/474380680

Pre-order

Mainly to improve the programming environment to improve programming efficiency, c are not part of the language itself, not directly compile them, must be compiled before the program, the first program of these special commands "pre-treatment." For example, the header file.

There are three categories: macro definition file contains conditional compilation.

Macro definitions (parameters into two kinds with no parameters)

Macro definition is replaced with a string macro name, it is a simple replacement, without checking correctness.

C is not a macro definition statement, do not add the line semicolon;

define command appears outside the program function, the limited scope of the definition of the macro name followed by a command to the end of the file origin.

#Undef command can be used to terminate Scope of macro definition.

A string of characters in a program by double prime enclosed, is not replaced.

Macro definition and the definition of variables, as only character replacement, does not allocate space;

Macro definition with parameters (not just a simple string replacement, but also for replacement parameter)

Macro definition with parameters with a function different, the following main points:

When the function is called, to determine the value of the argument expression, and then into parameter. The macro is just a simple character replacement.

Function call is in process when the program runs, is assigned a temporary parameter memory unit. And macro expansion is performed before compilation, not allocate memory means when deployed, the value transfer processing is not performed, there is no concept of "return value".

The arguments of the function and parameter types to be defined, both the requirements. The macro type is not a problem, no type of macro names. When the macro definition, the string may be any type of data.

Calling a function to obtain a return value only, and may try to get the macro definition with several results.

Use a macro number for a long time, after macro expansion source becomes longer, and the function call does not.

Macro substitution does not account for the running time, only compile time. The function calls accounted running time (to allocate memory to retain the scene, the return value)

File contains

The so-called "file contains a" process refers to the entire contents of a source file another source files can be included in, will soon contain additional files into this document. (#Include ...)

In addition to the file header can contain macro definitions and function prototypes, the structure may also include a global variable type definitions and definitions.

Conditional compilation

A part of the program will be compiled when required to meet certain conditions, that is, this part of the contents of the specified conditions compilation, which is conditional compilation.

Conditional compilation has the following forms:

#ifdef 标识符
    程序段1
#else
    程序段2
#endif
#if 表达式
    程序段1
#else
    程序段2
#endif
//条件编译
#include<stdio.h>
#define LETTER 1
void main()
{
    char str[20]="C Language",c;
    int i=0;
    while((c=str[i]!='\0'))
    {
        i++;
        #if LETTER
        if(c>='a'&&c<='z')
        c=c-32;
        #else
        if(c>='A'&&c<='Z')
        c=c+32;
        #endif
        printf("%c",c);
    }
    printf("\n");
 } 

The difference between # if, # ifdef, # if defined

#if instructions for use

Then later if that expression

#if (MAX==10)||(MAX==20)
 code...
#endif

Its role is: if (MAX == 10) || (MAX == 20) holds, then the compiler will put the code between the #if and #endif which translated into (Note: It is compiled in, not execution !!)

Use of #if defined

#If is connected to the back of a macro.

#if defined (x)
    ...code...
#endif

It does not matter that #if defined inside the "x" logic is "true" or "false" it just in front of the program's macro definition there is no definition of "x" This macro, if you define this macro x, then the compiler It will compile the middle of the ... code ... otherwise not directly overlooked the middle of the ... code ... code.

Further #if defined (x) can also be inverted, with it ** #if! Defined (x) **

Use the #ifdef

Ifdef consistent use and #if defined () usage

ifndef again, and #if! consistent with defined () usage.

Last stressed two points:
first: these macro definitions only to decide whether the code block is compiled!
Second: Do not forget #endif

Named existing types with typedef

Trap one:

Remember, typedef define a new type of alias, is different from the macro, it is not a simple string replacement. such as:

Define:

typedef char* PSTR;

then:

int mystrcmp(const PSTR, const PSTR);

const PSTR is actually equivalent to const char it? No, it is actually equivalent to char const.

The reason is that the entire given const const pointer to itself, i.e. the formation of a constant pointer char * const.

In short, remember when there together const and typedef, typedef will not be a simple string replacement on the line.

Trap II:

typedef keyword is syntactically a storage class (such as auto, extern, mutable, static, register, etc. as), storage characteristics although it does not really affect objects, such as:

typedef static int INT2; //不可行

Compilation fails, you are prompted to "specify more than one storage class."

1, typedef usage

In the C / C ++ language, typedef used to define an alias identifier and a keyword, which is part of the language of the compilation process, but it does not actually allocate memory space, as examples:

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 shortcomings "non-intuitive" and so on.

2, # define usage

(#Define statement is a macro definition, it is usually used to define the constant (including non-parametric and parametric band), as well as those used to achieve "good surface like, behind a long list of" macro, which itself is not performed during compilation but before that (pretreatment process) has been completed, but it is difficult to identify potential error codes and other maintenance issues, as an instance of it :)

#define   INT             int

#define   TRUE         1

#define   Add(a,b)     ((a)+(b));

#define   Loop_10    for (int i=0; i<10; i++)

Some analysts #define statements about abuses, as well as a good alternative in terms of Scott Meyer's Effective C ++ book 1, you can see.

3, the difference between #define and typedef

From the above it can also be the basic concept of clear, typedef is just a new name for the identifier in order to increase readability and other plays (just aliases), and was originally #define To define constants in C, to C ++, const, enum, inline appears that it has gradually become a tool from the alias. Sometimes it is easy to do both unclear and the use typedef in the end which is good, as this statement #define INT int, the same can be done with typedef, which is good use? He advocates the use of typedef, because in many of the early C compilers in this statement is illegal, but today's compilers has made expansion. For compatibility as much as possible, generally follow the #define definition of "readable" constants and macro statements of some tasks, while typedef is used to define a keyword, lengthy type of alias.

Macro definition simply string substitution (in situ expansion), rather than place the typedef expansion, its new name has some encapsulation, so that the newly named identifier has more functionality defined variables. See above the third row of the first large dot code:

typedef    (int*)      pINT;

And the following line:

#define    pINT2    int*

The same effect? But in reality different! See the difference in practice: pINT a, b; the same effect int * a; int * b; represents integer defines two pointer variables. And pINT2 a, b; the same effect int * a, b; represents an integer defines the integer variables and a pointer variable b.

1. First, two different execution times

Keyword typedef effective at compile time, because it is at compile time, so typedef functional type checking.

Define the macros, which occurs in the preprocessing stage, i.e. before compiling, and performs simple string replacement machine, without any inspection.

(#Define usage examples :)

#define f(x) x*x  
main( )  
{  
int a=6,b=2,c;  
c=f(a) / f(b);  
printf("%d \n",c);  
} 

The output of the program are: 36, fundamental reason is that simply #define string replacement, should be added parenthesis "(X * X)".

2. Different functions

Typedef used to define the type of alias, comprising not only these types of internal type (int, char, etc.), further comprising a custom type (e.g. struct), may function to easily memory function type.

Such as:

1.  typedef int (*PF) (const char *, const char *); 

Defines a pointer to a function of the data type PF, wherein the function returns a value of int, parameter const char *.

typedef has another important purpose, and that is the type of machine-independent definition, for example, you can define a floating-point type called REAL, on the target machine which i can get the highest accuracy:

1.  typedef long double REAL; 

That does not support long double machine, the typedef will look like the following:

1.  typedef double REAL; 

And, in support of not even double machine, the typedef will look like this:

1.  typedef float REAL; 

(#Define may be not only the type of alias, can also define constants, variables, compiler switch, etc.)

3. Different scopes

(#Define no limit scope, as long as it had before the predefined macros can be used in subsequent proceedings. The typedef has its own scope.)

void fun()   
{   
#define A int   
}  
void gun()   
{   
//在这里也可以使用A,因为宏替换没有作用域,   
//但如果上面用的是typedef,那这里就不能用A ,不过一般不在函数内使用typedef  
} 

4. The operation of the pointer

When both the modified pointer type, different roles.

Typedef int * pint;  
#define PINT int *  
Const pint p;//p不可更改,p指向的内容可以更改,相当于 int * const p;  
Const PINT p;//p可以更改,p指向的内容不能更改,相当于 const int *p;或 int const *p;  
pint s1, s2; //s1和s2都是int型指针  
PINT s3, s4; //相当于int * s3,s4;只有一个是指针

In fact, the label typedef and define the end is not the same, that we should not ignore this. Through the analysis of this article, I believe you already know the difference between the two. After grasp the distinction, it will be more flexible to use.

This article belongs to the author of all, please indicate the source http://www.cnblogs.com/iloverain/ . Without the consent of the author must be retained declared by this section, otherwise the right to pursue legal responsibilities.
Ali P7 Advanced Mobile Internet architect video (daily update) for free learning, please click: https://space.bilibili.com/474380680

Guess you like

Origin www.cnblogs.com/Android-Alvin/p/12109577.html