Thread: #define versus const (a beginner's question)

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    17

    #define versus const (a beginner's question)

    What is the difference between #define and const? And when do you use which?

  2. #2
    C > C++ duders ggs's Avatar
    Join Date
    Aug 2001
    Posts
    435
    a #define is handled by the preprocessor, which mashes up source files for the compiler to handle beforehand. const are like variables, but have a constant value. you can't use const to make macros such as

    #define MACRO(x) { x += 10 };

    if you wait, somebody will probably give a better answer. www.google.com would probably give the best answer of all.
    .sect signature

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    28

    #define vs. const

    This as an incomplete answer but might help.
    #define is a preprocessor facility used in C to define constants and macros among other things. The preprocessor goes through the source file and does a literal replacement of the values defined. In C a const only prevents the program from changing the value of the const variable.
    In C++ a const is used as a preprocessor tool instead of a #define. It lets the programmer "type qualify" the variable where #define cannot do that. Ex. #define number 33 vs. const int number = 33;
    There is a lot more to this. Check a good book on C/C++.
    rc7j

  4. #4
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    If you use #define, this will be processed by the preprocessor. So when you define

    #define MY_VALUE 10

    then everywhere in the code MY_VALUE appears, it is substituted by 10. But if you declare a const, you declare a constant variable and a variable takes memory. A constant variable can be used in almost the same way as a normal variable, but its value can't be changed. A defined value can't be used as a variable.

  5. #5
    The Artful Lurker Deckard's Avatar
    Join Date
    Jan 2002
    Posts
    633
    One key difference between using preprocessor defines and constants is type checking. I'll take compile-time warnings over run-time errors anyday :)
    Jason Deckard

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Polynomials and ADT's
    By Emeighty in forum C++ Programming
    Replies: 20
    Last Post: 08-19-2008, 08:32 AM
  2. Compiling error: Too many arguments.
    By Tuah in forum C++ Programming
    Replies: 16
    Last Post: 06-10-2008, 04:28 PM
  3. whats wrong here
    By sreetvert83 in forum C++ Programming
    Replies: 15
    Last Post: 09-21-2005, 10:05 AM
  4. FAQ: Directional Keys - Useing in Console
    By RoD in forum FAQ Board
    Replies: 38
    Last Post: 10-06-2002, 04:42 PM