"Effective C + +" Reading notes 02: Reduce the chance of #define appearances with Const,enum,inline

Source: Internet
Author: User

Before learning C language, our teacher taught us that it is best to define a number with a macro (#define). So that I have been accustomed to #define age 12.

In the C language environment, this is indeed an effective way to increase the readability of the program, but in C + +, you can have a more graceful implementation.

1. When you write down

#define NUMBER 11.12

If there is a compile error following the use of Nubmer, the compiler points out that the error occurred on 11.12 because the number has been replaced by 11.12 in the preprocessing process, and if the user is not you, it will certainly be confusing to 11.12, and it will take a lot of time to track it.

The replacement methods are:

const double Number = 11.12;

As a result, error positioning is definitely fine, and if you use this constant more than once, the macro substitution produces more than 11.12, which guarantees only one copy.

2. I have written such macro substitution code before:

#define MAX(a, b) ((a) > (b) ? (a):(b)) //得到两个数中的最大值

After adding parentheses outside each variable, there's really nothing wrong with using it. But the author uses this function in this way:

int a = 5, b = 0;
MAX(++a, b); //a会被递增两次
MAX(++a, b+10); //由于b+10>a,a只被递增一次!!

There's going to be a big problem!

In C + +, you can use the inline function to resolve:

template <typename T>
inline T MAX(const T& a, const T&b)
{
  return a > b ? a : b;
}

Using reference-to-const ensures that objects are not modified, and the inline function itself can be optimized at compile time to improve compilation speed.

Note:

1. For general constants, it is best to replace #define with Const and enum;

2. For macros like functions, it is best to replace #define with the inline function instead.

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.