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

Thread: const vs. enum very simple question

Hybrid View

  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.( "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

This is a survey!

HTML5 Development Center