The difference between enumerations and macros is resolved in detail

  • 2020-04-02 01:39:29
  • OfStack

There are several main differences between enumeration constants and macros:

1. Enumeration constants are one of the entities, but macros are not entities.

2. Enumeration constants are constants, but macros are not constants;

3. Enumeration constants have types, but macros have no types. Enumeration variables have the same properties as ordinary variables, such as scope, value, etc., but macros do not. Enumeration types are primarily used for restrictive input, for example, if a function's argument accepts only a finite number of values of a type and no other values are accepted, then enumeration is a good way to solve this problem. Use enumeration as much as possible, otherwise you won't see the value when debugging.

4. Using a macro to define a variable if you define the same variable depends on who's in front of it, and if the macro is in front of the variable you're going to get a compilation error, and it's going to be hard to find if the macro is too hidden. It's even scarier if the variable you defined is first, there are no errors directly, but the macro definition is quietly replaced by the custom variable. Using an enumeration definition will cause duplicate definition errors regardless of the order in which you define it. From the above example, enumerations are much better than macros. Another feature of macros is that they have no scope, which means that any code after the macro is defined can use the macro. Macros can be defined repeatedly which may cause the value of the macro to be changed. Therefore, it is recommended not to use macros to define variables that are plastic, use enumerations or const. Would it be useful to use const or enumeration, the world has always been so confusing, enumeration can only represent plastic, const can modify any type. In the case of shaping, if you want to define several related values then use enumeration, otherwise use const.


Related articles: