473,397 Members | 2,056 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Const Vs Macro

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?
Nov 13 '05 #1
3 13529
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.

--
Richard
Nov 13 '05 #2
"Richard Delorme" <ab****@nospam.fr> wrote in message
news:3f**********************@news.club-internet.fr...
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.

--
Richard


"const help to document the code and can make the code more robust. macros
often make the code more obfuscated."
Could you explain the statement above in more detail.......
And other places where you cannot you const.


Nov 13 '05 #3
arut wrote:
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 general, think of macros as a purely textual replacement. Think of a
const variable as being a read-only variable.

Because of the textual nature of preprocessing, macros are usually
considered less type-safe, beause type information is often not included
in the #define. You could try to get around this by casting the value
within the macro itself, but this is usually considered bad form because
it circumvents the C type system. Using type suffixes for numerical
values alleviates this problem, for the most part (ie 123UL notifies the
compiler that the type of 123 is unsigned long).

Scoping rules are also different. Macros have file scope, where const
variables have scope that corresponds to where they are declared.

There are several rules of thumb I use when deciding which to use.
There aren't that many hard and fast rules; for the most part it's all a
matter of degree.

1. If the scope that the 'constant' is used in is small or isolated,
prefer a const variable allocated in automatic storage (ie stack). It
will most likely be optimized away by your compiler.

2. If the constant will be used to specify the size for an array in
automatic storage, choose a macro (until I can recommend C99 VLA's in
good concience).

3. If you need a constant across a bunch of functions or files, use a
macro. Using a const variable with static storage (even if it's
declared static) will result in a permanent static storage location
being allocated for it.

4. If your expression is complicated, try to break it up into smaller
chunks of const variables that are initialized via macros:

/* Example of breaking down a complex calculation */
void do_calculation(float circle_radius)
{
/* Do some kind of complex calculation: */
const float area = PI * (circle_radius * circle_radius);
const float foo = (area * FROB_CONSTANT) % FLUX_DIVISOR;
/* Now do something with it... */
}
Now for the rules just about everybody agrees on. These are mandatory!

1. Always use all caps for macro names.
2. Always use underscores to seperate words in macro names.
3. Always use type suffixes for numerical constants.
I think I hit about everything. Did I leave anything out?

Mark
Mark Haigh
mf*****@sbcglobal.ten

Nov 13 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Simon | last post by:
Hi, I think this is slightly OT, (I am not certain that Macros are part of the standard), but I am hopping that someone could help. I am trying to use a language file in my system. the format...
22
by: johny smith | last post by:
I have never really understood the difference between 1.) #define NUMBER 1.653 vs. 2.) const double NUMBER = 1.653 I know that the #define is taken care of by the pre-processor and the...
3
by: Steven T. Hatton | last post by:
Sorry about the big code dump. I tried to get it down to the minimum required to demonstrate the problem. Although this is all done with GNU, I believe the problem I'm having may be more general. ...
19
by: Robert | last post by:
Greetings everyone, I was wondering if a const variable or object took up space. I know that a #define'd macro doesn't, as it's basically just interpreted by the compiler. If a const does take...
4
by: Pelle Beckman | last post by:
Hi, I saw this code in an earlier post (not that there's anything wrong with it) #include <iostream> using std::cout; const int hour = 3600; const int min = 60;
3
by: S Austin | last post by:
I would like to define a structure (a file header, in this case) that includes certain constants, and ensure that those members of the structure are always initialized to the same value. ...
5
by: sean345 | last post by:
While compiling my program I get the following g++ error: error: no matching function for call to `ErrorLog::file_error(std::string&, std::string&, const char)' note: candidates are: void...
20
by: subramanian100in | last post by:
Suppose I have #included <stdint.h> #define MAX_LINE_SIZE SIZE_MAX or const size_t maxLineLength = SIZE_MAX ; Between the above #define and const declaration, which should be...
7
by: miaohua1982 | last post by:
the code is as follows: #include<stdio.h> int arr={1,2,3,4,5,6,7}; #define size (sizeof(arr)/sizeof(arr)) int main() { int index = -1; int x = 0; int t;
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.