Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the better practice: global constant or #define? [duplicate]

Possible Duplicate:
C++ - enum vs. const vs. #define

Before I used #define I used to create constants in my main function and pass them where they were needed. I found that I passed them very often and it was kind of odd, especially array sizes.

More recently I have been using #define for the reason that I don't have to pass constants in my main to each individual function.

But now that I think of it, I could use global constants as well, but for some reason I have been a little hesitant towards them.

Which is the better practice: global constants or #define?

A side question, also related: Is passing constants from my main as I described a bad practice?

like image 494
Zac Blazic Avatar asked Dec 17 '22 16:12

Zac Blazic


2 Answers

They don't do quite the same thing. #define lets you affect the code at compilation time, while global constants only come into effect at runtime.

Seeing as #define can only give you extra trouble because there's no checking going on with how you use it, you should use global constants when you can and #define when you must. It will be safer and more readable that way.

As for passing constants from main, it's not unreasonable because it makes the called functions more flexible to accept an argument from the caller than to blindly pull it out of some global. Of course it the argument isn't really expected to change for the lifetime of the program you don't have much to gain from that.

like image 104
Jon Avatar answered May 05 '23 08:05

Jon


Using constants instead of #define is very much to be preferred. #define replaces the token dumbly in every place it appears, and can cause all sorts of unintended consequences.

Passing values instead of using globals is good practice. It makes the code more flexible and modular, and more testable. Try googling for "parameterise from above".

like image 38
Pete Avatar answered May 05 '23 08:05

Pete