What is the difference between #define n 10 and const int n=10

#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++.

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

#define n  10
int main ()
{
       // what would be the behavior of the below code.
       cout<< &n<<endl; 
       return 0;
}

2. macros are error prune
for example the below code

#define max(a,b)       ((a>b)?a:b)

int main ()
{
     int a = 2;
     int b = 3;
     cout<<max(a++, b)<<endl;
     return 0;
}

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. :).

commented: Excellent +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.