clause 02: Replace # define as const,enum,inline as possible

Source: Internet
Author: User

I. Overview

Minimize the use of preprocessor-macro substitution

Second, details

1. Constants for macro substitution

Old version: #define N 10;

New version: const int n = 10;

Comparison: #define不被视为语言的一部分, the tick name n is removed by the preprocessor before the compiler starts processing the source code.

Supplement: class's exclusive constants require encapsulation, and # define does not provide encapsulation (it does not value scopes).

2. Macros that resemble functions

Older version: #define CALL_WITH_MAX (A, B) f ((a) > (b)? (a): (b))

New version: Template<typename t> inline void Callwithmax (const t &a, const T &b) {f (a > B? a:b);}

Comparison: In older versions, there is a lot of constraint and complexity in invoking arguments, while inline is similar in efficiency but easy in form and error-prone.

Add: Callwithmax is a real function that adheres to scopes and access rules, and you can't write a class's private member function with a macro.

3. Enum has a const member, so it can be used as a constant expression

clause 02: Replace # define as const,enum,inline as possible

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.