Help me.

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Mar 2008
Posts: 21
Reputation: theausum has a little shameless behaviour in the past 
Solved Threads: 1
theausum theausum is offline Offline
Newbie Poster

Help me.

 
0
  #1
Apr 6th, 2008
What is the difference between #define n 10 and const int n=10
Reply With Quote Quick reply to this message  
Join Date: Feb 2008
Posts: 30
Reputation: BlackJavaBean is an unknown quantity at this point 
Solved Threads: 7
BlackJavaBean's Avatar
BlackJavaBean BlackJavaBean is offline Offline
Light Poster

Re: Help me.

 
0
  #2
Apr 6th, 2008
#define is preprocessor directive - it literally tells the preprocessor to replace n with 10 . const is actual C++ - it says that n is a constant of type int that is assigned the value 10. They'll do about the same thing, but are used for different reasons. In this case, n is a horrible choice for the variable name if #define is used because it could allow the preprocessor to insert 10's where you didn't mean for them to be. Another strike against the preprocessor is that it will define the constant globally - where as const follows scope restrictions native to C++.
Last edited by BlackJavaBean; Apr 6th, 2008 at 5:21 am. Reason: Added tags and update explanation
Reply With Quote Quick reply to this message  
Join Date: Jun 2006
Posts: 147
Reputation: Laiq Ahmed will become famous soon enough Laiq Ahmed will become famous soon enough 
Solved Threads: 20
Laiq Ahmed Laiq Ahmed is offline Offline
Junior Poster

Re: Help me.

 
2
  #3
Apr 6th, 2008
difference b/w const and #define (macro).

1. Type Checking:- macros are not type safe where as const are type safe. since the macros are replaced by definition at the time of preprocessing (which is done before compilation). the storage area of macros is not defined where as const has static storage area.

for example
  1. #define n 10
  2. int main ()
  3. {
  4. // what would be the behavior of the below code.
  5. cout<< &n<<endl;
  6. return 0;
  7. }

2. macros are error prune
for example the below code
  1.  
  2. #define max(a,b) ((a>b)?a:b)
  3.  
  4. int main ()
  5. {
  6. int a = 2;
  7. int b = 3;
  8. cout<<max(a++, b)<<endl;
  9. return 0;
  10. }
check the above code. the proper solution to above is to use templates rather than macros for specifying generic operatoins.
[see. Effective C++ for more details.].

so the conclusion is that use consts & templates where necessary don't use macros. .
Last edited by Laiq Ahmed; Apr 6th, 2008 at 8:25 am. Reason: forget to close code tag.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the C++ Forum


Views: 462 | Replies: 2
Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC