Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Why C++ enumerated types are better than macro definitions

Shulou Source: shulou.com Published: 2022-06-01 19:20:13 10月01日 Update

This article mainly explains why C++ enumerates types are better than macros. Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn why C++ enumerated types are better than macro definitions.

Enum.1: enumerated types are better than macro definitions

Reason (reason)

Macro definitions do not need to follow scope and type rules. At the same time, macro definition names are replaced at precompiled extremes, so they usually do not appear in tools such as debuggers.

Example (sample)

The first is some bad old-fashioned code:

/ / webcolors.h (third party header)

# define RED 0xFF0000

# define GREEN 0x00FF00

# define BLUE 0x0000FF

/ / productinfo.h

/ / The following define product subtypes based on color

# define RED 0

# define PURPLE 1

# define BLUE 2

Int webby = BLUE; / / webby = = 2; probably not what was desired

Use enumerations instead of:

Enum class Web_color {red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF}

Enum class Product_info {red = 0, purple = 1, blue = 2}

Int webby = blue; / / error: be specific

Web_color webby = Web_color::blue

We can use enumeration classes to avoid name conflicts.

Enforcement (implementation recommendations)

Marks the macro definition of the integer type.

At this point, I believe you have a better understanding of why C++ enumerated types are better than macros, so you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Types examples content names learning practical deeper bad code interests reasons at the same time practicality practicality tools suggestions simple operations integers methods more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Shulou Tech Info Redmi Apple NVidia