COMPUTER SCIENCE STRUCTURES

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 anew 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; Where type is any C++ data type and name is the newname for this type. This defines another name for the standard type of C++.

For example, you could create a new name for float values by using the following statement: typedef float amount;

This statement tells the compiler to recognize amount as an alternative name for float. Now you could create float variables using amount. amount loan, saving, installment; Using typedef does not replace the standard C++ data type name with the new name, rather the new name is in addition to the existing name. You still can create float variables using float. Once a new name has been defined by typedef, it can be used as a type for another typedef also.

Eg: typedef amount money; Now, this statement tells the compiler to recognize money as another name for amount, which itself is another name for float. Typedef does not create any new data types rather provides an alternative name for standard ypes. Reference provides an alias name for a variable and typedef provides an alias name for a data type.

2006 Delhi:

1.b) Illustrate the use of #define in C++ to define a macro.

2

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

1.C) Rewrite the following program after removing the syntactical error(s), if any.Underline each correction.

2

#include<iostream.h>
void main( )
{ struct STUDENT
{
char stu_name[20];
char stu_sex;
int stu_age=17;
}student;
gets(stu_name);
gets(stu_sex);
}

Ans:

#include<iostream.h>
#include<stdio.h>
void main( )
{ struct STUDENT
{ char stu_name[20];
char stu_sex;
int stu_age;
//Initialization of variables inside a structure is not allowed.
}student;
gets(student.stu_name);
cin>>student.stu_sex);
//A single character cannot be read using gets
}

 

CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )