CBSE eBooks CBSE Guess > eBooks > Class XII > Computer Science By . Mr. MRK
Chapter – 2. STRUCTURES 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 you compile the application. Eg: #define number 100 In this case every instance of “number” will be replaced by the actual number 100 in your code, and this means the final compiled program 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. • The #define allows you to make text substitutions before compiling the program. • The #define preprocessor can be used in the creation of macros (code substitution). 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 the application 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:. 1.#define: #define symbolic_constant value. Eg: #define number 100 //No semicolon ,no equal to symbol. 2.const: const type variable_name=value; Eg: const number=100; //Semicolon, equal to symbol. 2008 Outside Delhi: 1.a. What is the purpose of using a typedef command in C++?Explain with suitable example. 2 Ans: C++ allows you to define explicitly new data type names by using the keyword typedef. Using typedef does not actually create a new data class, rather it defines a new name for an existing type. This can increase the portability of a program as only the typedef statements would have to be changed. Typedef makes your code easier to read and understand. Using typedef can also aid in self documenting your code by allowing descriptive names for the standard data types. The syntax of the typedef statement is typedef type name; |