Raza Bayani

How to Group Related Values of Different Data-Types in C++

How to Group Related Values of Different Data-Types in C++

Suppose that you want to write a program to process student data. A student record consists of, among other things, the student’s name, student ID, GPA, courses taken, and course grades. Thus, various components are associated with a student. However, these components are all of different types. For example, the student’s name is a string, and the GPA is a floating-point number. Because these components and values are of different types, you cannot use an array to group all of the items associated with a student. C++ provides a structured data type called struct to group items of different types. Grouping components that are related but of different types offers several advantages. For example, a single variable can pass all the components as parameters to a function.

What is Struct and grouping values?

A collection of a fixed number of components in which the components are accessed by name. The components may be of different types.

The components of a struct are called the members of the struct. The general syntax of a struct in C++ is:

In C++, struct is a reserved word. The members of a struct, even though they are enclosed in braces (that is, they form a block), are not considered to form a compound statement. Thus, a semicolon (after the right brace) is essential to end the struct statement. A semicolon at the end of the struct definition is, therefore, a
part of the syntax.
The statement:


defines a struct employeeType with six members. The members firstNamelastName, address1, address2, and deptID are of type string, and the member salary is of type double.

Like any type definition, a struct is a definition, not a declaration. That is, it defines only a data type; no memory is allocated.

Variable Declaration with Struct:

Once a data type is defined, you can declare variables of that type. Let us first define a struct type, studentType, and then declare variables of that type.

These statements declare two struct variables, newStudent and student, of type studentType. The memory allocated is large enough to store firstName, lastName, courseGrade, testScore, programmingScore, and GPA.

Group Values with struct

Raza Bayani
Raza Bayani

Raza Bayani studies BCE (Bachelor in Computer Engineering) in Poly-technical University of Kabul. He is the CEO of CODEJOW group, a web designer, coder and recently a blogger. Raza thinks, he can help others and also boost-up his own programming skills being on codejow.com.

Related Posts
%d bloggers like this: