Reader small image

You're reading from  Learn C Programming. - Second Edition

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781801078450
Edition2nd Edition
Right arrow
Author (1)
Jeff Szuhay
Jeff Szuhay
author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay

Right arrow

Chapter 9: Creating and Using Structures

When a number of different kinds of values all pertain to a single thing, we can keep them organized with structures. A structure is a user-defined type. There may be multiple values in a structure and they may be of the same type or different types. A structure, then, is a collection of information representing a complex object.

With structures, not only can we represent complex objects more realistically, but we can also create functions that manipulate the structure in relevant ways. Just as data within a structure is grouped together in a meaningful manner, we can also group functions that manipulate the structure together in meaningful ways.

C is not an object-oriented programming (OOP) language. However, OOP has been a primary focus of programming languages and programming since the early 1990s. It is extremely likely that after you learn C, you will, at the very least, be exposed to OOP concepts. Therefore, after we learn about...

Technical requirements

As detailed in the Technical requirements section of Chapter 1, Running Hello, World!, continue to use the tools you have chosen.

The source code for this chapter can be found at https://github.com/PacktPublishing/Learn-C-Programming-Second-Edition/tree/main/Chapter09.

Understanding structures

It would be extremely easy for C programmers if the world were simply made up of objects that were only numbers or names. Imagine if everything were expressed as only a name or a series of numbers and nothing else. For example, an automobile vehicle identification number (VIN) precisely describes various attributes of that car and uniquely identifies it. On the other hand, humans are far more complex than automobiles. If not, perhaps the world would be a rather uninteresting place.

For C programs to solve real-world problems, they have to be able to model real-world complex objects. C allows various aspects of real-world objects to be abstracted and modeled via C structures. In the previous chapter, in a very basic way, we explored two such objects—playing cards and two-dimensional (2D) shapes. Did we explore every aspect of them? No.

In fact, we barely scratched the surface. For playing cards, we need to be able to describe all 52 cards in a...

Performing operations on structures – functions

Except for assignment, there are no intrinsic operations for structures. To perform any operation on a single structure or with two structures, a function must be written to perform the desired operation.

For example, earlier, we mentioned a function that can be used to compare two structures for equality. This must be done component by component, as follows:

bool isEqual( struct Card c1 , struct Card c2 )  {
  if( c1.suit != c2.suit ) return false;
  if( c1.face != c2.face ) return false;
  return true;
}

Notice that we did not compare every component of struct Card in this function. We'd only have to do that for absolute comparison and when we need to compare each and every component of both structures. This just isn't necessary for our card example.

Does it make sense to perform any or all mathematical operations on two structures? In general, no, but...

Structures of structures

A structure can contain components of any type, even other structures.

Let's say we want to represent a hand of five cards. We'll define a structure that contains five struct Card components, as follows:

struct Hand {
  int cardsDealt;
  struct Card c1; 
  struct Card c2;
  struct Card c3;
  struct Card c4;
  struct Card c5;
}

We could have just as easily written this as follows:

struct Hand {
  int cardsDealt;
  struct Card c1, c2, c3, c4, c5;
];

Both definitions are functionally identical. Do you see how this is similar to how variables of the same type were declared in Chapter 4, Using Variables and Assignments? As you work with C more and more, you will begin to see patterns being used repeatedly throughout the language. These repeated patterns make the language concise, consistent (for the most part), and easier to understand...

The stepping stone to OOP

OOP has been defined in many ways. At the core of all OO languages are objects. Objects are collections of data, much like C structures, and also operations on that data that are specific to that object, similar to C functions that operate on a structure. So, an object contains both its data and the set of operations that can be performed on it. Sometimes, the internals of the object are completely hidden to the outside program and its components are only available through functions with access to them, called accessors. This is a more self-contained version of C where functions are somewhat independent of the data or structures they operate on and must be passed the data that they manipulate. In C, a function—or a manipulator of data—is loosely tied or coupled to the data it manipulates.

In this chapter, we have used a set of data structures and enumerations to represent real-world cards. We also made functions specific to that data, such...

Summary

In this chapter, we learned about user-defined C structures. This is one of the most powerful ways of representing real-world objects in a cohesive and clear manner. First, we learned how to declare structures of our basic intrinsic types and custom types (enum). Then, we explored how to directly access and manipulate the components of C structures. The only simple operation that we can perform on structures in toto is the assignment operator.

We also explored how to manipulate structures via functions that access structure components and manipulate either the individual components, the entire structure, or multiple structures at the same time. We then expanded on the concept of what can be in a structure by defining structures of other structures. Finally, we learned that while C is not an OO language, we saw how C structures are the stepping stone to languages that are OO.

You may have found that, while using enums and structs, having to remember to add those keywords...

Questions

  1. How do you initialize a variable of struct someName to zero?
  2. How do you do a bitwise copy of one structure variable to another?
  3. What are the advantages of initializing the components of a structure variable at the time of declaration?
  4. What are the disadvantages of initializing the components of a structure variable at the time of declaration?
  5. Which data types may make up the components of a structure?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn C Programming. - Second Edition
Published in: Aug 2022Publisher: PacktISBN-13: 9781801078450
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay