(C++) difference between #define and const int,
Members - Reputation: 174
Posted 08 October 2006 - 12:42 AM
Members - Reputation: 2131
Posted 08 October 2006 - 01:04 AM
#define String std::string
const int myInt = 0;
is a better way of doing it because it creates a constant 'variable'. This avoids the use of the preprocessor, which is good for many reasons.
Members - Reputation: 410
Posted 08 October 2006 - 01:09 AM
// If you declare
#define BLUH 1+1
// and then you do
int myvariable = BLUH * 2;
// myvariable now equals 3!
// Because he preprocessor got through your code and did :
// int myvariable = BLUH * 2; // There's a BLUH, replace it by 1+1!
// int myvariable = 1+1 * 2; // And now this gives 3
// Of course you could do the following :
#define BLUH (1+1)
// and then it'd work (int myvariable = (1+1) * 2)
// but you'd better get used now to use constants
Members - Reputation: 530
Posted 08 October 2006 - 02:01 AM
Original post by OrangyTang
#define-s for constants aren't type safe. Where possible prefer const (or static const if appropriate) over defines.
In which cases would static const be appropriate over a standard const?
[How I broke into the Games Industry] [Why I left my Games Job]
[How to be a Games Tester] [Getting back into the Game]
Members - Reputation: 413
Posted 08 October 2006 - 02:32 AM
const int x=4;
#define y 5
z = 2*x; // slower - load from memory location and mult
z = 2*y; // faster - precompiled calc placed into instruction
Members - Reputation: 1402
Posted 08 October 2006 - 02:53 AM
*unless someone can prove me wrong on this