Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

const vs #defines

Status
Not open for further replies.

NaveenArora

Programmer
Sep 1, 1999
3
IN
Hi,<br>
I have small question<br>
1. i have heard one should never use #defines <br>
in c++. is it true ? if yes why ?<br>
2. if 1) is true then if i use const instead of #define<br>
wont it be more constly because #define<br>
will be replaced at compiler stage<br>
whereas const will occupy memory(read-only)<br>
or is compiler( i am using cfront one)<br>
every time intellegent enough to replace it<br>
based on context.<br>
<br>
Thanks
 
To answer your questions:<br>
<br>
1. The reason you should use const instead of #define is<br>
that const can be type checked by the compiler, which<br>
is not the case with #define . This allows you to use<br>
the full power of the C++ compiler to help you find<br>
bugs during compilation, which is much better than<br>
during runtime.<br>
<br>
2. According to B. Stroupstrup (The C++ Programming<br>
Language, Third Edition, pp. 95), the compiler <br>
can take advantage of an object being constant and<br>
just replace the object with its value, thereby saving<br>
the space it would otherwise have to allocate. Check the<br>
cfront documentation to see if they take advantage of<br>
this.<br>
<br>
Good luck!<br>
<br>
-Mart311
 
Yes I agree with Mart311. But both the methods have some pros and cons.<br>
Advantages of #defines :<br>
1) It enhances the readability of the program<br>
1) #defines are preprocessor directives. So usage of this reduces the burden from the compiler. For eg, <br>
#define MAX 100<br>
........<br>
char str[MAX}.<br>
<br>
Then whenever you want to change the size of your array. You need to change at one place only. Whereas if you use const word like <br>
const int x=100;<br>
char str[x];<br>
So x becomes a variable and compiler has to take care of this . Moreover if you look on the code below . Although you've declare i as a constant variable but even then you can change the value be redirecting by a pointer. Just compile this in unix .<br>
<br>
const int i = 100;<br>
int *x = &i;<br>
*x = 10;<br>
printf(&quot;now the value of i = %d&quot;,i);<br>
<br>
<br>
Disadvantages :<br>
As already mentioned by Mart311<br>
<br>
So it depends on your requirement . When and what to use. <br>
<br>
Does it answer you question ?<br>
Thanx<br>
Siddhartha Singh<br>
<A HREF="mailto:ssingh@aztecsoft.com">ssingh@aztecsoft.com</A><br>

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top