CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2002
    La Plata, Buenos Aires

    Lightbulb const vs. enum very simple question

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

    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
    Ontario, Canada
    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
    New Jersey
    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

    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

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.