CBSE Computer Science - Revision Tour(Solved)
CBSE Guess > eBooks > Class XII > CBSE Computer Science Structures Solved Revision Tour By Mr. Ravi Kiran
COMPUTER SCIENCE STRUCTURES
1.a) What is the difference between #define and const? Explain with suitable example.
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.
#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:
- The #define preprocessor allows u s to define symbolic names and constants.
#define PI 3.14159
- The #define allows you to make textsubstitutions before compiling the program.
#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.
- The #define preprocessor can be used in the creation of macros (code substitution).
#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;
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:
- #define: #define symbolic_constant value.
#define number 100 //No semicolon2,no equal to symbol.
- const: const type variable_name=value;
const number=100; //Semicolon,
equal to symbol.
CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )