Composite Data Types

Most languages support and encourage ways to group multiple pieces of data together. General term for these is composite data types, data that made from smaller pieces of data. For example when you want to keep track of your favorite video games, you can write it multiple times like this :

string title = "Donkey Kong"
string publisher = "Nintendo"
int year = 1981
boolean completed = true

string game2title = "Final Fantasy"
string game2publisher = "Square Enix"
int game2year = 1997
boolean game2completed = false

There are no actual structure here, and you just repeating yourself with different variable. So what most language support is the way to define your own data types.

//define the new data type
struct Game {
    string title
    string publisher
    int year
    boolean completed
}

The most common way to defining new data type is using struct. Inside this code block we defining four variable. Now, we still not create any of this. We defining a new type, like string or int, called Game. Variable now can use this type when they defined.

//define the new data type
struct Game {
    string title
    string publisher
    int year
    boolean completed
}

//create a variable of that type
Game firstGame
//use dot syntax to access member of variables
firstGame.title = "Donkey Kong"
firstGame.publisher = "Nintendo"
firstGame.year = 1981
firstGame.compeleted = true

And now we have self contain variable named firstGame that contain four information. We can create variable named secondGame easily using the same way.

It maybe look more complicated, but it's actually have more benefit than just writing so many variables. One is that as we start writing more complex code, we will be passing information from one part of our program to another, and it's lot easier to pass a single Game variable than have to pass all individual element we create differently.

results matching ""

    No results matching ""