Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Const VS Defines

Const VS Defines

Scheduled Pinned Locked Moved C / C++ / MFC
c++questionvisual-studio
21 Posts 11 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Offline
    C Offline
    chaq686
    wrote on last edited by
    #1

    I was wondering what is the best way to set constanta in C/C++. Using a header file with all constants set as #defines? Kind of like:

    #define pi (3.1416f)
    #define gravity_m_div_sqrt_secs (9.81f)

    Or, set as static members of a class?

    // Common.h
    #ifndef __COMMON__
    #define __COMMON__

    class Common{

    public:
    static float k_pi;
    static float k_gravity_m_div_sqrt_secs;

    };

    // Common.cpp
    #include "Common.h"

    float Common::k_pi = 3.1416f;
    float Common::k_gravity_m_div_sqrt_secs = 9.81f;

    It think is better to set 'em as a class, because sometimes you need to access them in any part of the code. And if you modify any one of them, the compilation time will be faster. But then I think how much RAM will these constants will be use, so in that case #defines are useful. I really want to know your opinion.

    P F C O A 6 Replies Last reply
    0
    • C chaq686

      I was wondering what is the best way to set constanta in C/C++. Using a header file with all constants set as #defines? Kind of like:

      #define pi (3.1416f)
      #define gravity_m_div_sqrt_secs (9.81f)

      Or, set as static members of a class?

      // Common.h
      #ifndef __COMMON__
      #define __COMMON__

      class Common{

      public:
      static float k_pi;
      static float k_gravity_m_div_sqrt_secs;

      };

      // Common.cpp
      #include "Common.h"

      float Common::k_pi = 3.1416f;
      float Common::k_gravity_m_div_sqrt_secs = 9.81f;

      It think is better to set 'em as a class, because sometimes you need to access them in any part of the code. And if you modify any one of them, the compilation time will be faster. But then I think how much RAM will these constants will be use, so in that case #defines are useful. I really want to know your opinion.

      P Offline
      P Offline
      PIEBALDconsult
      wrote on last edited by
      #2

      Waaaay... back in the 90s, the company's guru said to always use defines -- to save memory. :sigh: We know better now.

      C 1 Reply Last reply
      0
      • P PIEBALDconsult

        Waaaay... back in the 90s, the company's guru said to always use defines -- to save memory. :sigh: We know better now.

        C Offline
        C Offline
        chaq686
        wrote on last edited by
        #3

        That's a PRETTY good point. But at least you agree with me to set the define for each .cpp file and not all of them in one header file. One modification and BAM, at least 15 minutes to compile for one little change!

        P 1 Reply Last reply
        0
        • C chaq686

          That's a PRETTY good point. But at least you agree with me to set the define for each .cpp file and not all of them in one header file. One modification and BAM, at least 15 minutes to compile for one little change!

          P Offline
          P Offline
          Peter_in_2780
          wrote on last edited by
          #4

          The converse point is also true. A typo in one place can lead to almost unfindable bugs. Cheers, Peter

          Software rusts. Simon Stephenson, ca 1994. So does this signature. me, 2012

          1 Reply Last reply
          0
          • C chaq686

            I was wondering what is the best way to set constanta in C/C++. Using a header file with all constants set as #defines? Kind of like:

            #define pi (3.1416f)
            #define gravity_m_div_sqrt_secs (9.81f)

            Or, set as static members of a class?

            // Common.h
            #ifndef __COMMON__
            #define __COMMON__

            class Common{

            public:
            static float k_pi;
            static float k_gravity_m_div_sqrt_secs;

            };

            // Common.cpp
            #include "Common.h"

            float Common::k_pi = 3.1416f;
            float Common::k_gravity_m_div_sqrt_secs = 9.81f;

            It think is better to set 'em as a class, because sometimes you need to access them in any part of the code. And if you modify any one of them, the compilation time will be faster. But then I think how much RAM will these constants will be use, so in that case #defines are useful. I really want to know your opinion.

            F Offline
            F Offline
            Freak30
            wrote on last edited by
            #5

            I would go the second way, mostly for not polluting the global namespace. Also you should set the types to static const float, assuming they are not supposed to change during runtime. I like to name constants in all upper case, but that's just a personal preferrence.

            The good thing about pessimism is, that you are always either right or pleasently surprised.

            1 Reply Last reply
            0
            • C chaq686

              I was wondering what is the best way to set constanta in C/C++. Using a header file with all constants set as #defines? Kind of like:

              #define pi (3.1416f)
              #define gravity_m_div_sqrt_secs (9.81f)

              Or, set as static members of a class?

              // Common.h
              #ifndef __COMMON__
              #define __COMMON__

              class Common{

              public:
              static float k_pi;
              static float k_gravity_m_div_sqrt_secs;

              };

              // Common.cpp
              #include "Common.h"

              float Common::k_pi = 3.1416f;
              float Common::k_gravity_m_div_sqrt_secs = 9.81f;

              It think is better to set 'em as a class, because sometimes you need to access them in any part of the code. And if you modify any one of them, the compilation time will be faster. But then I think how much RAM will these constants will be use, so in that case #defines are useful. I really want to know your opinion.

              C Offline
              C Offline
              CPallini
              wrote on last edited by
              #6

              What about enums?

              O 1 Reply Last reply
              0
              • C CPallini

                What about enums?

                O Offline
                O Offline
                Orjan Westin
                wrote on last edited by
                #7

                Enums aren't useful for anything but integer constants.

                C 1 Reply Last reply
                0
                • O Orjan Westin

                  Enums aren't useful for anything but integer constants.

                  C Offline
                  C Offline
                  CPallini
                  wrote on last edited by
                  #8

                  OOOPS! :-O :-O Didn't see the type of the consts. Thank you, I am going to delete my post.

                  1 Reply Last reply
                  0
                  • C chaq686

                    I was wondering what is the best way to set constanta in C/C++. Using a header file with all constants set as #defines? Kind of like:

                    #define pi (3.1416f)
                    #define gravity_m_div_sqrt_secs (9.81f)

                    Or, set as static members of a class?

                    // Common.h
                    #ifndef __COMMON__
                    #define __COMMON__

                    class Common{

                    public:
                    static float k_pi;
                    static float k_gravity_m_div_sqrt_secs;

                    };

                    // Common.cpp
                    #include "Common.h"

                    float Common::k_pi = 3.1416f;
                    float Common::k_gravity_m_div_sqrt_secs = 9.81f;

                    It think is better to set 'em as a class, because sometimes you need to access them in any part of the code. And if you modify any one of them, the compilation time will be faster. But then I think how much RAM will these constants will be use, so in that case #defines are useful. I really want to know your opinion.

                    O Offline
                    O Offline
                    Orjan Westin
                    wrote on last edited by
                    #9

                    Don't use #define for constants. If you want to keep things tidy, use a dedicated namespace, and a separate definition.

                    // constants.h
                    namespace constants
                    {
                    extern const float pi;
                    }

                    // constants.cpp
                    #include "constants.h"

                    namespace constants
                    {
                    const float pi = 3.141593;
                    }

                    // application.cpp
                    ...
                    int i = 5;
                    float angle = constants::pi * i;
                    // the code below won't work if you use #define
                    int* pi = &i;
                    ...

                    This also demonstrates why using #defines will break your code

                    S 1 Reply Last reply
                    0
                    • O Orjan Westin

                      Don't use #define for constants. If you want to keep things tidy, use a dedicated namespace, and a separate definition.

                      // constants.h
                      namespace constants
                      {
                      extern const float pi;
                      }

                      // constants.cpp
                      #include "constants.h"

                      namespace constants
                      {
                      const float pi = 3.141593;
                      }

                      // application.cpp
                      ...
                      int i = 5;
                      float angle = constants::pi * i;
                      // the code below won't work if you use #define
                      int* pi = &i;
                      ...

                      This also demonstrates why using #defines will break your code

                      S Offline
                      S Offline
                      SoMad
                      wrote on last edited by
                      #10

                      When using namespaces (in Visual Studio) you get the added benefit of IntelliSense helping you out. I personally think it is overkill to put the definition in a cpp file as long as we are talking about simple constants. Soren Madsen

                      "When you don't know what you're doing it's best to do it quickly" - Jase #DuckDynasty

                      A O 2 Replies Last reply
                      0
                      • S SoMad

                        When using namespaces (in Visual Studio) you get the added benefit of IntelliSense helping you out. I personally think it is overkill to put the definition in a cpp file as long as we are talking about simple constants. Soren Madsen

                        "When you don't know what you're doing it's best to do it quickly" - Jase #DuckDynasty

                        A Offline
                        A Offline
                        Albert Holguin
                        wrote on last edited by
                        #11

                        SoMad wrote:

                        I personally think it is overkill to put the definition in a cpp file as long as we are talking about simple constants.

                        I'd second that... plus if someone is tracking a value of a constant, it's getting hidden away a bit (unnecessarily) by putting it in a source file.

                        1 Reply Last reply
                        0
                        • C chaq686

                          I was wondering what is the best way to set constanta in C/C++. Using a header file with all constants set as #defines? Kind of like:

                          #define pi (3.1416f)
                          #define gravity_m_div_sqrt_secs (9.81f)

                          Or, set as static members of a class?

                          // Common.h
                          #ifndef __COMMON__
                          #define __COMMON__

                          class Common{

                          public:
                          static float k_pi;
                          static float k_gravity_m_div_sqrt_secs;

                          };

                          // Common.cpp
                          #include "Common.h"

                          float Common::k_pi = 3.1416f;
                          float Common::k_gravity_m_div_sqrt_secs = 9.81f;

                          It think is better to set 'em as a class, because sometimes you need to access them in any part of the code. And if you modify any one of them, the compilation time will be faster. But then I think how much RAM will these constants will be use, so in that case #defines are useful. I really want to know your opinion.

                          A Offline
                          A Offline
                          Albert Holguin
                          wrote on last edited by
                          #12

                          Although using the statics is a way to keep your namespace cleaner, the macros are used A LOT... and they allow your code to be compiled as C OR C++. If you use class/namespace enclosed statics you're pretty much C++ compliant only.

                          D S 2 Replies Last reply
                          0
                          • S SoMad

                            When using namespaces (in Visual Studio) you get the added benefit of IntelliSense helping you out. I personally think it is overkill to put the definition in a cpp file as long as we are talking about simple constants. Soren Madsen

                            "When you don't know what you're doing it's best to do it quickly" - Jase #DuckDynasty

                            O Offline
                            O Offline
                            Orjan Westin
                            wrote on last edited by
                            #13

                            The benefit of having the definition in a cpp file is more apparent when the constant isn't a universal physical/mathematical one, but one that could conceivably change during development. Should this happen, there's no need to recompile all files that refer to it, which would be required if the definition is in the header file.

                            1 Reply Last reply
                            0
                            • A Albert Holguin

                              Although using the statics is a way to keep your namespace cleaner, the macros are used A LOT... and they allow your code to be compiled as C OR C++. If you use class/namespace enclosed statics you're pretty much C++ compliant only.

                              D Offline
                              D Offline
                              Daniel Pfeffer
                              wrote on last edited by
                              #14

                              In my experience, very few projects have a requirement that they be compilable as both C and C++. Many libraries must be accessible from both C and C++, but a well-designed C-style interface will take care of that. For example, instead of:

                              #define MAX_SIZE 42

                              write a function,

                              int GetMaxSize()

                              which returns the value of the constant from your library. This has the further advantage of decoupling the library from the constant - any changes to MAX_SIZE won't require the client's code to be recompiled (possibly relinked, if we are talking about a static library).

                              If you have an important point to make, don't try to be subtle or clever. Use a pile driver. Hit the point once. Then come back and hit it again. Then hit it a third time - a tremendous whack. --Winston Churchill

                              A 1 Reply Last reply
                              0
                              • D Daniel Pfeffer

                                In my experience, very few projects have a requirement that they be compilable as both C and C++. Many libraries must be accessible from both C and C++, but a well-designed C-style interface will take care of that. For example, instead of:

                                #define MAX_SIZE 42

                                write a function,

                                int GetMaxSize()

                                which returns the value of the constant from your library. This has the further advantage of decoupling the library from the constant - any changes to MAX_SIZE won't require the client's code to be recompiled (possibly relinked, if we are talking about a static library).

                                If you have an important point to make, don't try to be subtle or clever. Use a pile driver. Hit the point once. Then come back and hit it again. Then hit it a third time - a tremendous whack. --Winston Churchill

                                A Offline
                                A Offline
                                Albert Holguin
                                wrote on last edited by
                                #15

                                Well in my experience, there's A LOT of code that exists from the C days, so you still see macros a lot. And yes, most people use C style interfaces for libraries. Important to note that the original question specified C AND C++. I was simply pointing out that namespace/class enclosed statics aren't C compliant.

                                Quote:

                                I was wondering what is the best way to set constanta in C/C++

                                D 1 Reply Last reply
                                0
                                • A Albert Holguin

                                  Well in my experience, there's A LOT of code that exists from the C days, so you still see macros a lot. And yes, most people use C style interfaces for libraries. Important to note that the original question specified C AND C++. I was simply pointing out that namespace/class enclosed statics aren't C compliant.

                                  Quote:

                                  I was wondering what is the best way to set constanta in C/C++

                                  D Offline
                                  D Offline
                                  Daniel Pfeffer
                                  wrote on last edited by
                                  #16

                                  Perhaps I expressed myself poorly. I was referring to the case where the library is written in C / C++ / <whatever>, but must be callable from a C-style interface (e.g. the MS-Windows SDK). I believe that it is poor practice to expose _#define_d constants in the library's header file, because it introduces tight coupling between the caller and the library - any change in the constant requires recompiling the client. Having said that, I recognize that standard C practice is to define such constants, so that code such as below may be written: header.h:

                                  #define MAX_SIZE 42
                                  ...

                                  code.c:

                                  #include "header.h"

                                  void foo(void)
                                  {
                                  int array[MAX_SIZE];

                                  ...
                                  }

                                  C99 and later support variable-length arrays. As developers transition to compilers supporting this feature, I suspect that the need for such constants may decrease.

                                  If you have an important point to make, don't try to be subtle or clever. Use a pile driver. Hit the point once. Then come back and hit it again. Then hit it a third time - a tremendous whack. --Winston Churchill

                                  S 1 Reply Last reply
                                  0
                                  • A Albert Holguin

                                    Although using the statics is a way to keep your namespace cleaner, the macros are used A LOT... and they allow your code to be compiled as C OR C++. If you use class/namespace enclosed statics you're pretty much C++ compliant only.

                                    S Offline
                                    S Offline
                                    Stefan_Lang
                                    wrote on last edited by
                                    #17

                                    You still could use a const struct in ANSI C like this:

                                    const extern struct {
                                    double pi;
                                    int answer;
                                    } constants = { 3.14, 42 };

                                    const is part of ANSI C, as are struct initializer lists. So no need to resort to #defines and cluttering the global namespace. Of course, you could also just define each individual constant as const, or you could skip the const and the initialization if you prefer initializing the values in a .c file.

                                    GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                                    1 Reply Last reply
                                    0
                                    • D Daniel Pfeffer

                                      Perhaps I expressed myself poorly. I was referring to the case where the library is written in C / C++ / <whatever>, but must be callable from a C-style interface (e.g. the MS-Windows SDK). I believe that it is poor practice to expose _#define_d constants in the library's header file, because it introduces tight coupling between the caller and the library - any change in the constant requires recompiling the client. Having said that, I recognize that standard C practice is to define such constants, so that code such as below may be written: header.h:

                                      #define MAX_SIZE 42
                                      ...

                                      code.c:

                                      #include "header.h"

                                      void foo(void)
                                      {
                                      int array[MAX_SIZE];

                                      ...
                                      }

                                      C99 and later support variable-length arrays. As developers transition to compilers supporting this feature, I suspect that the need for such constants may decrease.

                                      If you have an important point to make, don't try to be subtle or clever. Use a pile driver. Hit the point once. Then come back and hit it again. Then hit it a third time - a tremendous whack. --Winston Churchill

                                      S Offline
                                      S Offline
                                      Stefan_Lang
                                      wrote on last edited by
                                      #18

                                      You still can use the const keyword. In case of constants being used for array bounds, you could instead declare an enum (since const ints in C cannot be used for array bounds, unfortunately):

                                      enum {
                                      MAX_SIZE = 42
                                      };
                                      const struct {
                                      double pi;
                                      int size;
                                      } constants = { 3.14, 42 };
                                      double arr1[MAX_SIZE]; // ok in C and C++
                                      double arr2[constants.size]; // ok in C++, error in C

                                      GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                                      D 1 Reply Last reply
                                      0
                                      • S Stefan_Lang

                                        You still can use the const keyword. In case of constants being used for array bounds, you could instead declare an enum (since const ints in C cannot be used for array bounds, unfortunately):

                                        enum {
                                        MAX_SIZE = 42
                                        };
                                        const struct {
                                        double pi;
                                        int size;
                                        } constants = { 3.14, 42 };
                                        double arr1[MAX_SIZE]; // ok in C and C++
                                        double arr2[constants.size]; // ok in C++, error in C

                                        GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                                        D Offline
                                        D Offline
                                        Daniel Pfeffer
                                        wrote on last edited by
                                        #19

                                        1. Your solution, while removing the problems with #define, still has the problem of tight coupling of the caller's code with the library. 2. In C99 or later, variable-length arrays are perfectly legal, but IIRC - not as static variables.

                                        If you have an important point to make, don't try to be subtle or clever. Use a pile driver. Hit the point once. Then come back and hit it again. Then hit it a third time - a tremendous whack. --Winston Churchill

                                        S 1 Reply Last reply
                                        0
                                        • C chaq686

                                          I was wondering what is the best way to set constanta in C/C++. Using a header file with all constants set as #defines? Kind of like:

                                          #define pi (3.1416f)
                                          #define gravity_m_div_sqrt_secs (9.81f)

                                          Or, set as static members of a class?

                                          // Common.h
                                          #ifndef __COMMON__
                                          #define __COMMON__

                                          class Common{

                                          public:
                                          static float k_pi;
                                          static float k_gravity_m_div_sqrt_secs;

                                          };

                                          // Common.cpp
                                          #include "Common.h"

                                          float Common::k_pi = 3.1416f;
                                          float Common::k_gravity_m_div_sqrt_secs = 9.81f;

                                          It think is better to set 'em as a class, because sometimes you need to access them in any part of the code. And if you modify any one of them, the compilation time will be faster. But then I think how much RAM will these constants will be use, so in that case #defines are useful. I really want to know your opinion.

                                          D Offline
                                          D Offline
                                          den2k88
                                          wrote on last edited by
                                          #20

                                          I usually use consts or better still enums. The main problem I came to find with defines is namespace pollution - in many places you'd have constants named MAX_FILENAME_LENGHT and it is possible, depending on the use you make of this constant, that they differ. Using a define you'd probably end up with a redefine or nasty bug somewhere, using constants and enums you can keep them enclosed in a class, which is often what is needed. Enums are still better as they build another inner namespace, further reducing namespace pollution. For the same reason I often enclose the data members that makes sense only when taken together into inner structs inside the definition of the classes, this way you have an easy way to pass an entire block of information between functions and can reuse common names (as Length used with different meanings in different places, avoiding C-like horrors like DataPadLenght, DataPayloadLenght, DataReservedAllocationLength, FileNameLenght...).

                                          Geek code v 3.12 GCS d--- s-/++ a- C++++ U+++ P- L- E-- W++ N++ o+ K- w+++ O? M-- V? PS+ PE- Y+ PGP t++ 5? X R++ tv-- b+ DI+++ D++ G e++>+++ h--- r++>+++ y+++* Weapons extension: ma- k++ F+2 X

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups