A
arut
I would like to know when a const should be used and when a #define is necessary
in a program using a constant. What are the pros and cons?
in a program using a constant. What are the pros and cons?
I would like to know when a const should be used and when a #define is
necessary in a program using a constant. What are the pros and cons?
Richard Delorme said:arut a écrit :
I would like to know when a const should be used and when a #define is
necessary in a program using a constant. What are the pros and cons?
'const' means that an object is read-only, not that its value is constant.
Macro are mostly here to make typing easier. In C, a number written with
digits (and optionnaly a type specifier) is called a constant.
for example :
- 3.1415926 is a constant with type double and the value 3.1415926.
- #define M_PI 3.1415926
allows you to type only M_PI instead of 3.1415926 in your code.
- On the other hand :
const double K_PI = 3.1415926;
creates a variable that is read-only. If you use K_PI in your code, you are
using a variable with the value 3.1415926, not directly the value
3.1415926.
In place where the C language need a constant, you can use a macro that will
be replaced by a constant, but you cannot use a const variable :
const int K_SIZE = 10;
#define M_SIZE 10
enum {E_SIZE = 10};
int array1[K_SIZE]; /* wrong, K_SIZE is read-only but not a constant */
int array2[M_SIZE]; /* ok, M_SIZE will be replaced by the constant 10 */
int array3[E_SIZE]; /* ok, enumerations are constant too */
IMHO, using const as much as you can and avoiding macros is a good
programming practice. const help to document the code and can make the code
more robust. macros often make the code more obfuscated.
arut said:I would like to know when a const should be used and when a #define is necessary
in a program using a constant. What are the pros and cons?
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.