CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2011
    Posts
    35

    [RESOLVED] #define vs. int, double, etc

    Why use #define preprocessor directive to declare constants when they can be declared with int = or double =

    What advantage does #define have?

  2. #2
    Join Date
    Jul 2011
    Posts
    35

    Re: #define vs. int, double, etc

    #define can tell the compiler not to compile the same header two or more times.
    Reference: http://www.learncpp.com/cpp-tutorial...-preprocessor/

  3. #3
    Join Date
    Jul 2002
    Location
    Portsmouth. United Kingdom
    Posts
    2,727

    Re: [RESOLVED] #define vs. int, double, etc

    Quote Originally Posted by CodingFreak View Post
    What advantage does #define have?
    Not a lot.
    There are very few instances in which I find #define to be necessary.
    Code in macros are hard to debug.
    Macros do not respect namespaces and struct/class definitions.

    e.g.
    Anyone who has tried to define a member function called 'GetMessage' under Windows will have come across the error message stating that 'GetMessageA' was not defined.
    "It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
    Richard P. Feynman

  4. #4
    Join Date
    Jan 2009
    Posts
    1,689

    Re: [RESOLVED] #define vs. int, double, etc

    #define has uses other than defining constants. It's very useful for manipulating things where inline functions aren't capable of doing what you want, or using compiler specific optimizations on code that may be compiled on multiple compilers.

    Code:
    #ifdef __GNUC__
        #if ((__GNUC__ * 100 + __GNUC_MINOR__) >= 403)
    	   #define HOTSPOT __attribute__ ((hot))
        #else
    	   #define HOTSPOT
        #endif
    #else
        #define HOTSPOT
    #endif
    
    void methodThatGetsCalledAlot(void) HOTSPOT;  //can create dramatic increase in performance due to code localization
    void methodThatGetsCalledAlot(void){
        //code
    }
    Last edited by ninja9578; August 12th, 2011 at 12:03 PM.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured