0% found this document useful (0 votes)
4 views5 pages

C++ Structures and Macros Explained

Uploaded by

gogoiabinash300
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

C++ Structures and Macros Explained

Uploaded by

gogoiabinash300
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUT

Chapter 13 – Structure

Conceptual Question/Answer
Q. What is a structure?
 A structure is a collection of logically related variables referenced under one name. e.g.
struct TIME{
int hr; int min; int sec;
}
Q. How are the following related to one another:
a) structures and arrays
 Arrays bring together a group of items of the same data type whereas structures bring together
a group of related data items of any data type.
b) structures and classes
 Structure is actually a class in C++, declared with keyword 'struct'. By default, all the members
are public in a structure by default, on the other hand, all members are private by default in
classes.
Q. How a structure does differs from an array?
 Structure Array
i) A collection of heterogeneous elements. i) A collection homogeneous elements.
ii) Accessed by its object with a (.) dot operator. ii) Accessed by its subscript or index.
iii) User-defined data type. iii) Derived data type.
Q. How a structure does differs from a class?
 Structure Class
i) Start with the keyword 'struct'. i) Start with the keyword 'class'.
ii) Collection of data only. ii) Collection of data and its associated function.
iii) By default data are public. iii) By default data are private.
Q. What is #define?
 The #define is a pre-processor directive that creates symbolic constants represented as symbols and
macros.
Q. State the two forms of the #define directive?
 i) Defining a constant as, #define PI 3.141
ii) Defining a parameterized macro as, #define MAX(a, b) ((a) > (b) ? (a) : (b))
Q. Illustrate the use of #define in C++ for defining a macro.
 A macro refers, to a #define definition that is used to define words to enhance readability and
understand ability. Before compilation the pre-processor replaces every occurrence of macro as per
the definition e.g.,
#define PI 3.141, will replace every occurrence of PI with 3.141 within the program.

IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUT
IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUT

Q. What do you mean by const constant in C++? Or, What is the use of const in C++? Explain with an
example?
 Constant is something that doesn't change. In C++ the keyword 'const' is used to make program
elements such as variables, function arguments and parameters etc. constant i.e., which cannot be
modified/altered once declared in the whole execution of the program.
e.g. const double PI=3.141;
Q. How #define differs from a const constant?
 i) Both #define and const are definining constant, however #define can only define simple
constants, while const can define almost any type of C++ constant, including things like structure
classes.
ii) The #define constants used in the program is not visible to the compiler since they get replaced
with their values by the pre-processor prior to compilation. But, the constants defined with const
are visible to compiler and the compiler checks the syntax of const statements as per language
rule and follows normal C++ scope rules.
Q. What do you mean by typedef in C++? Explain with an example? Or, What is the use of typedef?
 Typedef, stands for type definition, is a keyword that allows the programmer to create new names or
an alias names for existing data types such as int, float etc. or more commonly used templates types
in C++ such as structure etc. It enhance readability and understand ability of the program.
e.g., All transactions in a bank generally involves amounts which are frequently of double data type.
So, to enhance the program readability, we can provide an alias name for data type double, as
typedef double Amounts;
Now, we can define any transaction as
Amounts loan, installment, balance, interest;
Q. Declare a structure in C++ with name, roll number and total marks as components?
 struct STD{
char name[20];
int roll;
float total;
};
Q. Consider the following structure of a STUDENT
struct STUDENT{
int admno;
char sname[30];
float aggr;
}std1;

IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUT
IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUT

With reference to the above structure, illustrate briefly how can you -
a) Refer each individual element of the structure
 Each individual structure elements are referenced using (.), the dot operator as per following
syntax:
structure_name.element_name or structure_object.element_name
e.g. [Link] or [Link]
b) Intialize structure elements
 Either by using separate assignment statements for its individual elements outside the structure,
after its object declaration or at time of its object initialization by surrounding its values with
braces. e.g.
[Link]=1001;
strcpy([Link],'Rajib');
[Link]=80.5;
or,
STUDENT std2={1001,'Rajib',80.5}
c) Assign structure object
 Structure assignment is possible only if both the structures and object are of same structure
type. e.g.
STUDENT std3 = std1;
Application based Question/Answer
Q. i) Declare the following structures as specified:
 ADDRESS (street, city, zipcode)
 STUDENT(admno, sname, stream and addr), where addr is an object of structure ADDRESS
ii) Create an object std for the structure STUDENT.
iii) Initialize the admno as 1101, stream as "Science" and city as "Duliajan" for the object.
 struct ADDRESS{
char street[50];
char city[20];
long zipcode;
};
struct STUDENT{
int admno;
char sname[30];
char stream[15];
ADDRESS addr;
};
STUDENT std;

IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUT
IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUT

[Link] = 1101;
strcpy([Link],"Science");
strcpy([Link],"Duliajan");
Q. Observe the following structure definition carefully:
struct PartItem{
char Number[10];
float Price;
int Qty;
};
struct Assembly{
char Name[10];
PartItem PartA[3];
}
i) Write a C++ code to define a structure variable called Motor.
ii) Assign name "PowerPlug" and Assign its first part number as "SMR0001", its price as 3.57 and
the quantity needed as 7.
iii) Then read in the three members for the second part.
iv) Print the data for the third part.
 i) Assembly Motor;
ii) strcpy([Link],"PowerPlug");
strcpy([Link][0].Number,"SMR0001");
[Link][0].Price = 3.75;
[Link][0].Qty = 7;
iii) gets([Link][1].Number);
cin>>[Link][1].Price>>[Link][1].Qty;
iv) cout<< [Link]<<endl;
[Link][2].Number<<[Link][2].Price<<[Link][2].Qty;
Q. Consider the following structure STUDENT and its object.
struct STUDENT {
int roll;
char sname[20];
float theory;
float practical;
};
STUDENT rec[10];

IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUT
IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUT

Assume all the required header files are declared. Write a function SHOWTOPPER() in C++ that reads
the structure object and print the records for the student whose total score (theory+practical) is more
than 80.
void SHOWTOPPER(){
float total;
for(int i=0; i<10; i++){
total = rec[i].theory + rec[i].practical;
if(total>80)
cout<<rec[i].roll<<rec[i].sname<<rec[i].theory<<rec[i].practical<<endl;
}
}

***************************

IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUTORIAL POINT IP CS TUT

Common questions

Powered by AI

Structures default to public access, suitable for data-centric models where direct access to members is needed. Classes default to private, aligning with OOP principles of encapsulation by hiding data and exposing only operations through functions . Thus, choosing between them can be strategic; classes offer encapsulation and data protection, while structures are straightforward for POD (Plain Old Data) representations, influencing design based on application data interaction needs.

Structures in C++ allow groups of logically related variables of different data types to be treated as a single entity, accessed via dot notation, making them user-defined data types . On the other hand, arrays comprise homogeneous elements, meaning all elements are of the same type and accessed through indexing, making them derived data types . This impacts usage significantly; structures are suitable for representing complex data models with various attributes, while arrays are ideal for managing sequences of similar data types efficiently.

'SHOWTOPPER' reads structure objects, calculating total scores and conditionally printing student details if the score exceeds 80 . It encapsulates principles of abstraction through function use and demonstrates control structures with a loop iterating over records and an 'if' condition to enforce logic. This highlights structured programming by separating logic from data representation, encouraging modular and maintainable code.

The struct Assembly example shows the declaration of an array of structures 'PartA' within 'Assembly', highlighting how each part of 'Assembly' is accessed individually via index and has its attributes accessed using dot notation . It demonstrates handling sets of similar elements under a unified structure, allowing indexed manipulation within larger structures, thus offering a powerful mechanism for managing collections of complex, related data consistently.

With structures defaulting to public access, they are typically suited for data aggregation without complex behavior, fostering simplicity and speed . Classes, with private default, support encapsulation and information hiding, critical for secure, maintainable, and extensible software design following OOP principles . This distinction influences the strategic application of these constructs depending on the balance needed between simplicity, accessibility, and security in a given design context.

'#define' is a pre-processor directive that defines symbolic constants, which are replaced by their values before compilation, making them invisible to the compiler . 'const', however, can define any C++ constant type and is checked by the compiler, adhering to scope rules . This means 'const' provides type safety and better integration with C++ features, while '#define' offers simplicity in defining simple constants.

Structure elements in C++ can be initialized using separate assignment statements after the structure's declaration or using brace-enclosed initializations at declaration time . Assignment is possible only if structures or their objects are of the same type, allowing direct assignment from one object to another . This process promotes clearer, more organized code, allowing for flexible data manipulation and easy maintenance by encapsulating related data.

The STUDENT structure, incorporating ADDRESS as a member, reflects real-world relationships by modeling a comprehensive student entity comprising identification, academic details, and address . This approach exemplifies abstraction, allowing data to mirror real entities and interactions, thus promoting intuitive design and enhancing the applicability of programs to solve real-life problems.

'typedef' in C++ creates new names for existing data types, enhancing code readability by allowing intuitive naming relevant to their use context, such as 'Amounts' for financial transactions instead of 'double' . This abstraction aids in maintenance by providing clarity and reducing the cognitive load on programmers, thus aiding collaboration and reducing errors related to datatype misinterpretations.

Structures in C++ can include other structures as components or objects, achieved by defining a structure and incorporating it within another structure as a member . This encapsulation allows for the logical organization and representation of complex hierarchical data models, reflecting real-world relationships and enabling modular design, code reuse, and simplification of composite data handling.

You might also like