Curiosity Question

This is a discussion on Curiosity Question within the C++ Programming forums, part of the General Programming Boards category; My teacher was talking about constant variables, and I was thinking that since the variable is assigned a value when ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    411

    Curiosity Question

    My teacher was talking about constant variables, and I was thinking that since the variable is assigned a value when its declared and never changes, would it not be faster to use a #define? That is unless the value was based on some runtime event/calculation?

    EX:

    #include <iostream.h>

    const int DOZEN = 12;

    main() {
    cout << "There are " << DOZEN << " units in a Dozen.\n";
    }


    wouldnt it be faster to use the #define in a case like this? Since define is a preprocessor directive, and all instances of it will just be replaced with the number at compile time, it wouldnt have to access memory for the variable would it?

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    155
    The low down using defines for constant variables is ill advised because of lack of type checking by the preprocessor. For simple defines like a constant int it's probably not as big a deal, but for more complicated defines your'e better off in the long run using const int (whcih can't be changed by anything at all during run time by the way), or so the guru's say.

  3. #3
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    In C++ as long as you don't use the address of a const or declare one as extern, no storage should be allocated for it. In this case it will just as efficient as using #define, but with the benefit of type checking.
    zen

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  2. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  3. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 08:22 PM
  4. Question about linked lists.
    By cheeisme123 in forum C++ Programming
    Replies: 6
    Last Post: 02-25-2003, 12:36 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 12:47 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21