Structures


You didn't think you'd actually learned everything there was to know about the core of C++, did you? Well, you're in for a shock -- there's still a whole chapter of syntax and functions to pour through! Not to worry though. This is critical stuff, we know; and if you take your time reading it, we'll take our time writing it.

You might have been wondering how to make records in C++ (Or maybe you haven't, but smile and nod). It's really not that different than in Pascal; in fact, the biggest difference is probably going to be what it's called : a Structure. Let's start by comparing the record in Pascal with the structure in C++:

Pascal:

Mexican = RECORD
    Tasty : Boolean;
    Color : Integer;
    Rating: Integer;
    CookTime : Real;
END;

C++

struct mexican {
    bool tasty;
    int color;
    int rating;
    float cooktime;
};

Take a good look at both, and notice how very similar they really are. When you consider the differences in the way the code is written, structures in C++ really do seem as if they're only slightly different from the way Pascal does things. Now that you've seen how to declare them, let's try using them in a program:

void main(void)
{
   mexican lunch;

   lunch.tasty = false;
   lunch.color = 0;
   lunch.rating = 0;
   lunch.cooktime = 5542.2;

   cout << "Status of my lunch:" << endl;

   if (lunch.cooktime > 5000)
       cout << "I wouldn't know, I'm waiting for it!\n";
   else {
       if (lunch.tasty)
            cout << "Yum!\n";
       else
            cout << "Yuck! *Barf* Yech eeww!\n";
   }
}

Let's go over what that program does. In the first line, it creates lunch, of type mexican. Then, it assigns values to each of variables inside the structure. Luckily, this is exactly how you'd do it in Pascal. The next couple of statements check the values that have been assigned, and print out a message depending on what you have the variables set to. If you have a huge cooktime value, the program prints out "I wouldn't know, I'm waiting for it!"; if you don't, it checks to see whether or not the food is tasty. Yes, not the most useful program, but you can never be too careful when it comes to checking your lunch.


Table of Contents

Structures | Pointing to Structures | Using Pointers to Structures | Using Escape Codes
Shortcuts | Exercises