C Language # define keywords, Conditional compilation and predefined symbolic knowledge details,

Source: Internet
Author: User

C Language # define keywords, Conditional compilation and predefined symbolic knowledge details,
I. pre-defined symbols

The C standard defines the following five preprocessing symbols

_ FILE _ 
// name of the source FILE to be compiled _ LINE _/current row number of the FILE _ DATE _/DATE of FILE compilation _ TIME __
/ /file Compilation Time _ STDC _ 
// If the compiler complies with ansi c, the value is 1. Otherwise, it is undefined.

We will use these preprocessing symbols in the case of file input/output and output logs, such

#include 
 
  #include 
  
   #define LOG f

printf(pf,"%d %d %d %d\n",\            __FILE__,__LINE__,__DATE__,__TIME__,__STDC__)

int main(){    

int i = 0;  

  FILE* pf = fopen("log.txt","w");w   

 if(pf == NULL)    {      

  printf("open failure!\n");      

 exit(EXIT_FAILURE);   

 }    

for(i = 0; i < 5; i++)   

{     

  LOG;    

}    

fclose(pf);    

return 0;

}

\ + Carriage return: a line break, an escape character. It cannot be followed by any character other than carriage return. Otherwise, an error is reported.

Ii. # define keywords

# Define has two functions: one is the definition identifier and the other is the definition macro.

1. Define the identifier
//#define name stuff#define MYINT int//typedef stuff nametypedef int MYINT;

Do not add a semicolon to the identifier defined by define

2. Definition macro

# The define mechanism includes a rule that allows you to replace a parameter with a text. This implementation is usually called a macro or a definition macro.

//#define name(parament-list) stuff
#define MAX ((a)>(b)?(a)(b))
int a = MAX(11+2,11-2);
//int a = ((11+2)>(11-2)?(11+2):(11-2));

Macro definitions should never be left in parentheses to prevent unexpected consequences due to priority issues. Macros cannot implement recursive macros, only text replacement, and do not simplify the calculation of the content in string without macro replacement.

# Define X 100 printf ("X"); // no macro replacement # And ##
3. # And ##

The compiler automatically concatenates two adjacent strings into one

#: Insert a parameter to a string

# A-> ""

#define PRINT(x,format)
\printf("the value of "#a" is "#format"\n",x)
//printf("the value of ""x"" is""format""\n",x)
int a = 10;PRINT(x,"%d");

# You can combine the symbols on both sides into one symbol

#define CAT(x,y) 
((x)##(y))
int num5 = 10;CAT(num,5);
//=num5

4. Macro and function comparison ① There is no macro type check

No type check is a major feature of macros (but it is also a hidden danger) and can accomplish functions that are not possible for many functions.

#define MALLOC(n,type)\        (type*)malloc(n*sizeof(type))
② Macros have no additional overhead such as function call and return, and are more efficient,

However, when the logic is complex and the code size is huge, the call overhead and return overhead are smaller than the calculation time, which can be omitted.

③ Macros are only text replacements and cannot be debugged. ④ macros may increase the code length. ⑤ if a function parameter is an expression, the input parameters are calculated based on the expression results.

If the macro parameter is an expression, it will only Replace the text and will not be calculated.

Conclusion: There are many advantages and disadvantages. macro is used for small amount of code, and function is used for large amount of code. In C ++, the macro concept is abandoned and inline is used. We recommend that you do not use macros Based on the advantages and disadvantages.

5. macro parameters with side effects
Int a = 10; int B = 0; B = a + 1; B = a ++; // an expression with side effects to change

Do not input parameters with side effects to macro parameters

6. Naming Conventions

MACRO: all uppercase

Function: not all uppercase

Exceptions

// Whether getchar () is implemented by the library function or by the macro implementation is determined by the compiler # define getchar () getc ()

# Undef name // cancel macro identifier name Definition

3. Conditional compilation 1. If you have defined DEBUGStatement execution. Otherwise, the statement is not executed.
# Define _ DEBUG _ 1 # ifdef _ DEBUG _ statement; # endif
2. Conditional compilation
# If constant expression (true compilation, false, not compiled) Statement; # endif
3. multi-branch condition Compilation
# If constant expression statement; # elif constant expression statement; # endif
3. Determine if it is defined
#ifndef __DEBUG__//==>#if !defined(__DEBUG__)#ifdef __DEBUG__//==>#if defined(__DEBUG__)
4. nested commands

Pre-processing commands can be nested

Pragma onec // New Style prevents header files from being referenced multiple times 
// tedious # ifndef _ TEST_H __# define _ TEST_H __# endif/_ TEST_H __

IV. Other 1. header file inclusion
# Include// Directly go to the database directory to find # include "filename"
 // first find the current working directory and then go to the database directory to find

2. # error "…"

# A compilation error occurs when an error occurs.

3. strcpy ();

The source string must end with '/0', and the target string address is returned.
Whether the target space can be placed or not, the function returns the target string.

4. assert (Condition Statement)

Make good use of assertions. the header file is

5. Chain Reaction

The return value of this function can be used as the parameter of the next function to achieve the effect of chain reaction.

Printf ("% d \ n", strlen (strcpy (p, "hello world !")));

6. Common Errors:

Compilation errors

You can directly check the compiler error message for a link-type error.

Function Name, variable name error, Library File Usage error (third-party library) running error


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.