const vs. enum very simple question
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: const vs. enum very simple question

Hybrid View

  1. #1
    Join Date
    Dec 2002
    Location
    La Plata, Buenos Aires
    Posts
    615

    Lightbulb const vs. enum very simple question

    It is true that the following definition on a header file:
    Code:
    enum { cg = 1 };
    is better that the this...?

    Code:
    const int cg = 1;
    the document says that the second does not allocate any memory space , so it operates like a standard #define in C.(http://www.metagraphics.com/pubs/Met...odingGuide.pdf "Metagraphics coding guide")

  2. #2
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    2,236
    It depends. If you are defining a single value, then you should use a constant. If you are defining multiple values to be used together, then you should use an enum. Enum is often used in a class declaration in place of a constant because some compilers do not allow you to set the value of the const inline. ie. you can't write this:

    class c
    {
    const int x = 0;
    };

    but you can write

    class c
    {
    enum { x = 0 };
    };

  3. #3
    Join Date
    Aug 2000
    Location
    New Jersey
    Posts
    968
    I recomend that you always use enums when possible.
    Most compilers will not let you initialize a constant variable inside the class declaration.
    However all C++ compilant compilers will let you set the enum value in the header.

    By putting the value in the header, it makes your code less ambiguous.

    The only draw back with the enum method, is that if you change the value, you have to recompile all source files referencing the header.
    Where as using the const method, you only have to recompile the *.cpp file that contains the initialized variable.
    David Maisonave
    Author of Policy Based Synchronized Smart Pointer
    http://axter.com/smartptr


    Top ten member of C++ Expert Exchange.
    C++ Topic Area

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center