简体   繁体   中英

Is enum a macro or integer variable in C++?

Is an enum a macro or a variable in C++? I am confused about macros in C++. What is the definition of macro in C++?

Enum

In c++ there are two kinds of enum :

  1. enum classes
  2. plain enums

This is how to declare them:

enum Day { sunday, monday, tuesday };  // plain enum
enum class Color { red, green, blue }; // enum class

What is the difference?

enums - The enumerator names { sunday, monday, tuesday } are in the same scope as the enum and their values implicitly convert to integers and other types.

enum class - enumerator names { red, green, blue } are local to the enum and their values do not implicitly convert to other types (like another enum or int )

It is generally accepted that enum class is preferred to plain enum because it is part of the c++ type system, they don't convert implicitly to int , they don't pollute the namespace, and they can be forward-declared. Using enum class can protect you from some bugs that can arise form plain enum .

Macro

A macro is a totally different thing. Macros are used by the preprocessor, which is a program that process the source code before compilation. Macros are a piece of code in a program which is given some name. Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code. The #define directive is used to define a macro. For example:

#include <iostream> 
  
// macro definition 
#define LIMIT 5 

int main() 
{ 
    for (int i = 0; i < LIMIT; ++i)
    { 
        std::cout << i << "\n"; 
    }  
} 
0
1
2
3
4

A macro can also act like a function

#include <iostream> 
  
// macro with parameter 
#define AREA(l, b) ((l) * (b)) 

int main() 
{ 
    int a = 10, b = 5, area; 
  
    area = AREA(a, b); 
  
    std::cout << "Area of rectangle is: " << area; 
} 
Area of rectangle is: 50

The macro is replaced by the preprocessor so there is no function call. This can make code run faster, however, in c++ functions can be inlined by the compiler which is preferred over using macros. Macros can be problematic if you don't define and use them carefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM