Difference between Enum and Define Statements

后端 未结 18 2563
终归单人心
终归单人心 2020-11-30 00:27

What\'s the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?

For exampl

18条回答
  •  臣服心动
    2020-11-30 01:02

    Enums are generally prefered over #define wherever it makes sense to use an enum:

    • Debuggers can show you the symbolic name of an enums value ("openType: OpenExisting", rather than "openType: 2"
    • You get a bit more protection from name clashes, but this isn't as bad as it was (most compilers warn about re#defineition.

    The biggest difference is that you can use enums as types:

    // Yeah, dumb example
    enum OpenType {
        OpenExisting,
        OpenOrCreate,
        Truncate
    };
    
    void OpenFile(const char* filename, OpenType openType, int bufferSize);
    

    This gives you type-checking of parameters (you can't mix up openType and bufferSize as easily), and makes it easy to find what values are valid, making your interfaces much easier to use. Some IDEs can even give you intellisense code completion!

提交回复
热议问题