Results 1 to 6 of 6
  1. #1
    Join Date
    Oct 2004
    Posts
    25

    #define vs. using a constant

    Hi all, just got done watching C++_i3_03_GameLoop VTM. I noticed when they were limiting the frames per second they used a "#define" statement to store the value to compare against the current time. I was wondering why you wouldn't use a constant instead like:

    PHP Code:
    const float GAME_SPEED 33.33
    Just wondering since I tried running it with this statement and had no problems.

  2. #2
    Join Date
    Jun 2003
    Location
    Trier, Germany
    Posts
    1,350
    it's basically just a matter of taste.
    #define, like all of the preprocessor-features is considered to be bad style by some guys, but like i said above: just a matter of taste in the end...

    (at least not for this particular problem )

  3. #3
    Join Date
    Oct 2004
    Posts
    25
    Well I was talking with someone today and the way the explained it was that with a "#define" statement you can access that variable from any class as long as the class you instantiated is still in existance and with a "constant" it is private to the class/function it is within. Does this hold any water?

  4. #4
    Join Date
    Sep 2003
    Posts
    9
    defince vs const

    when you you use a const along witht the statement you supply what the variable is suppose to be. In your example you put

    const float GAME_SPEED = 33.33;

    now you know for now on when you use the variable GAME_SPEED it is type float. If you were going to use define you don't have the luxary of defining the variables type which in the example may not seem like much but when you start coding complex data the ability to supply the variable type is very handy especally if you need to do any type of checking. My advice is to always use const whenever possible.

  5. #5
    Join Date
    Jan 2004
    Location
    South Pole
    Posts
    1,519
    Well, back in the old days, when there was just C, #define was the only way to define constants. So a lot of people still do it that way. Nowadays, it is generally recommended to use "const" for constant values. One reason, as zentec pointed out, is because of the fact that you can (actually you have to) specify the type, which keeps you from making silly mistakes. Another reason is that you can make it local to a function, or any other block of code. Also, namespaces, if I'm not mistaken.

    About being able to access it from anywhere, if you put it at the top of your program (same place you put #define), you can still access it from any class.

  6. #6
    Join Date
    Oct 2004
    Posts
    25
    Thanks for helping clear this up for me.

Posting Permissions

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