2008 Delhi:
1.a) What is the difference between #define and const? Explain with suitable example.
2
Ans: While they both serve a similar purpose,#define and const act differently. When using #define the identifier gets replaced by the specified value by the compiler, before the code is turned into binary. This means that the compiler makes the substitution when youcompile the application.
Eg:
#define number 100
In this case every instance of “number” will be replaced by the actual number 100 in yourcode, and this means the final compiledprogram will have the number 100 (in binary).
#define with different types of data:
Eg:
#define PI 3.14159
Eg:
#define MAX 70
Before compilation, if the C++ preprocessor finds MAX as one word, in the source code, it replaces it with the number 70.
Eg:
#define SQUARE(x) x*x
Before compilation, if the C++ preprocessor finds SQUARE(x), where x is any value in the source code, it replaces it with its square (ie x*x). Here a macro substitutes text only; It does not check for data types. On the other hand, when we use const and the application runs, memory is allocated for the constant and the value gets replaced when theapplication is run.
Syntax: const type variable_name=value;
Eg:
const int a=10;
The value of a constant is fixed and in the above example, the value for a in entire program is 10 only. You cannot change the value of a, since it is declared as constant.
Difference between #define and const in declaration:
Eg:
#define number 100 //No semicolon2,no equal to symbol.
Eg:
const number=100; //Semicolon, equal to symbol.
CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )