Use Enum or #define?

I create a toy interpreter, and I implemented a token class that contains the type and value of the token.

The token type is usually an integer, but how should I abstract the int?

What would be the best idea:

// #defines
#define T_NEWLINE 1
#define T_STRING 2
#define T_BLAH 3

/**
 * Or...
 */

// enum
enum TokenTypes
{
   t_newline = 1,
   t_string = 2,
   t_blah = 3
};
+3
source share
9 answers

Enumerations can be carried over to int; moreover, they are the preferred way to list predefined values โ€‹โ€‹in C ++. Unlike #defines, they can be placed in namespaces, classes, etc.

Alternatively, if you want the first index to start at 1, you can use:

enum TokenTypes
{
   t_newline = 1,
   t_string,
   t_blah
};
+15
source

Enums (, "print x" "" ). #defines (.. , ).

.

+4

.

-, #define C. โ€‹โ€‹C++, , , , ... .

. , , , , , .

:

// ints
const int T_NEWLINE = 1;

struct Tokens { static const int T_FOO = 2; };

// enums
enum { T_BAR = 3; }; // anonymous enum

enum Token { T_BLAH = 4; }; // named enum

// Strong Typing
BOOST_STRONG_TYPEDEF(int, Token);
const Token NewLine = 1;
const Token Foo = 2;

// Other Strong Typing
class Token
{
public:
  static const Token NewLine; // defined to Token("NewLine")
  static const Token Foo;     // defined to Token("Foo")

  bool operator<(Token rhs) const { return mValue < rhs.mValue; }
  bool operator==(Token rhs) const { return mValue == rhs.mValue; }
  bool operator!=(Token rhs) const { return mValue != rhs.mValue; }

  friend std::string toString(Token t) { return t.mValue; } // for printing

private:
  explicit Token(const char* value);

  const char* mValue;
};

.

  • int , , .
  • enum , , - ( ).
  • StrongTypedef enum. int.
  • - , , ( , ).

, int enum, , , #define: const , .

+3

, , , , . , .

+1

Enum , , intellisense. , Enum, , #define, .

. const versus define C/++, , #define.

?

+1

enum

#define , .

0

: , , t_blah (, ), t_blah ( ), int.

0

enum . , , .

, enum - . .

enum color
{
  red,
  green,
  blue,
  unknown
};

, #define ( const, )

0

, , - : ++ 0x :)

enum class Color /* Note the "class" */
{
   Red,
   Blue,
   Yellow
};

,

  • -: int color = Color::Red; . Color color Red int.
  • . ( ++ 98): enum class Color : unsigned short. unsigned short .
  • ( ): Red undefined; Color::Red. , , , , , ( "", "", "", e tc).
  • : enum class Color; , Color , ( , ); class Test;, Test *.
0

Source: https://habr.com/ru/post/1739205/


All Articles