The struct ceo_member we discussed previously takes quite a lot of memory. For example, why do we allocate a ten byte string for the machine type, since we've only got three different machines? You'd argue that we could use a single byte to store this information. You'd be right! We can and should do this. One way to do it is by making machine a char. Then, different values would ‘mean’ different machines. There's a nicer way: an enumerated data type, known as an enum in C:

enum Machine {oric_1, atmos, telestrat};

Here we define a new data type, called enum Machine (not just Machine). It can take three values: oric_1, atmos, or telestrat. We can define variables of this type and use them in the normal way:

{
	enum Machine my_oric;
 
	my_oric = telestrat;
	printf ("I have an Oric");
	switch (my_oric) {
	case oric_1:
		printf ("-1!\n");
		break;
	case atmos:
		printf (" Atmos!\n");
		break;
	case telestrat:
		printf (" Telestrat!\n");
	}
}

This is nothing but an int with special values declared for it! You can safely do arithmetic (for example, if I'm upgrading from an Atmos to a Telestrat, I can write my_oric++;). In fact, the symbols you name in the enum definition are assigned an integer value, starting at 0 and increasing. So, oric_1==0, atmos==1 and telestrat==2. You can override this and set the assigned values by yourself:

enum Machine {oric_1=0, atmos=10, telestrat=20};

You can even have different constants share the same values. If a value for a constant is left out, it's set to the value of the previous constant in the enum plus one. There is one argument against making extensive use of enums: they're as big as an int, which is 4 bytes for the 32-bit compiler and 2 bytes for the 16-bit one. Of course, this means that, unlike Pascal, enums in C can have more than 256 different values. On the Oric, though, this is more of a curse than a blessing...

Tags: 


Add new comment

Leave a comment