📄 define.html
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head> <meta name="generator" content= "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org"> <title>#define</title> <link href="../cppreference.css" rel="stylesheet" type="text/css"></head><body><table> <tr> <td> <div class="body-content"> <div class="header-box"> <a href="../index.html">cppreference.com</a> > <a href= "index.html">C/C++ Pre-processor Commands</a> > <a href= "define.html">#define</a> </div> <div class="name-format"> #define </div> <div class="syntax-name-format"> Syntax: </div> <pre class="syntax-box"> #define macro-name replacement-string</pre> <p>The #define command is used to make substitutions throughout the file in which it is located. In other words, #define causes the compiler to go through the file, replacing every occurrence of <em>macro-name</em> with <em>replacement-string</em>. The replacement string stops at the end of the line.</p> <div class="related-examples-format"> Example code: </div> <div class="related-examples"> <p>Here's a typical use for a #define (at least in C):</p> <pre class="example-code"> #define TRUE 1 #define FALSE 0 ... int done = 0; while( done != TRUE ) { ... } </pre> <p>Another feature of the #define command is that it can take arguments, making it rather useful as a pseudo-function creator. Consider the following code:</p> <pre class="example-code"> #define absolute_value( x ) ( ((x) < 0) ? -(x) : (x) ) ... int x = -1; while( absolute_value( x ) ) { ... } </pre> <p>It's generally a good idea to use extra parentheses when using complex macros. Notice that in the above example, the variable "x" is always within it's own set of parentheses. This way, it will be evaluated in whole, before being compared to 0 or multiplied by -1. Also, the entire macro is surrounded by parentheses, to prevent it from being contaminated by other code. If you're not careful, you run the risk of having the compiler misinterpret your code.</p> <p>Here is an example of how to use the #define command to create a general purpose incrementing for loop that prints out the integers 1 through 20:</p> <pre class="example-code"> #define count_up( v, low, high ) \ for( (v) = (low); (v) <= (high); (v)++ ) ... int i; count_up( i, 1, 20 ) { printf( "i is %d\n", i ); } </pre> </div> <div class="related-name-format"> Related topics: </div> <div class="related-content"> <a href="sharp.html">#, ##</a><br> <a href="preprocessor_if.html">#if, #ifdef, #ifndef, #else, #elif, #endif</a><br> <a href="undef.html">#undef</a> </div> </div> </td> </tr> </table></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -