High-end tip: How to use #define to define variables

Source: Internet
Author: User
Introduction

To define a variable in the source file that is related to the line number, it is too slow to manually enter each time. This article describes how to use macro definitions to define variables related to line numbers.

For example, we want to define a shape variable such as a_10 in the 10th line of the source code. use macro definition to accomplish mission

In the definition of macros, there are two special operators in standard C + +: #和 # #. #是用于给红参数添加双引号; # #用于链接两个宏参数, now that you can connect two macro parameters, we can link a first letter and line number as a whole.

So, we wrote this:

#define MM (A) a# #__LINE__
int main () {
int MM (C);
}

After compiling, we found that the c__line__ variable was not what we wanted. Why, then?
Because the compiler does not unfold the __line__ when preprocessing, but sees it as a whole. What to do.
We can expand the line number by redefining another macro, and then call the macro as a parameter.

#define AA (B,C) b# #C
#define BB (b,c) AA (b,c)
#define DD (A) BB (a,__line__)
int main () {
int DD (V);
}

OK, we have successfully defined the variables associated with the line number.

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.