Chapter 2: Data types in QBasic
|
2.1 |
Introduction
Data type is a fancy terminology that defines what a variable is contrained to. For example, you know that:
X% = 150 X% is a variable contrained to an INTEGER type. So an INTEGER is a data type, so is SINGLE, DOUBLE, etc.
|
2.2 |
QBasic supported Data Types
QBasic doesn't support a lot of data types, but you usually won't need them all anyway. QBasic supports INTEGER, LONG, SINGLE, DOUBLE, and STRING. If you want the whole story, you can click on Help|Contents then click on Data Types. |
2.3 |
How to use each Data Type
As we've seen before:
X% = 150
Y! = 15.15
Z& = 102980 X% is an INTEGER, but what is Y! and Z&
If you see an '!' (exclamation mark), after a variable name, it means that variable is constrained to a SINGLE. If you see an '&' sign after the variable name, it means that variable is constrained to a LONG. As an exercise, find out what sign you use for a DOUBLE, and STRING.
|
2.4 |
An alternative way
Instead of doing what we did above to define the data type of each variable, there's actually a few alternatives:
DIM X AS INTEGER
DIM Y AS SINGLE
DIM Z AS LONG As you can tell, this is much easier on the eyes, not surprisingly this is termed 'Good Programming Style.' Just in case you really want to confuse people, here's yet another alternative that works:
DEFINT X
DEFSNG Y
DEFLNG Z Looks fine doesn't it? Haha, I'll let you figure out the problem behind this as an exercise. You may never have to worry about it, but unless you know what you're really doing, this is not good programming style.
|
2.5 |
User-Defined Data Types
You can define your own data types, but not the kind you might be thinking of. It would be nice if we could define BYTE, WORD, DWORD, etc. However, it's not possible in QBasic, but what we can define is our own data structures. Think about an address book, what information would you want in it?
TYPE AddressBookType
Address AS STRING * 50
ZipCode AS STRING * 50
Person AS STRING * 50
Phone AS STRING * 50
END TYPE That should be enough, I hope you follow, just look up TYPE in the help file if you don't understand how TYPE works. So how do we use this information? First, we must attach a variable that is constrained to the AddressBookType. If you followed everything up to this point, I think you'll know what to do:
DIM AddressBook AS AddressBookType The variable AddressBook is now constrained to the AddressBookType. To store information into our AddressBook, we can do this:
AddressBook.Address = "7 Heaven St."
AddressBook.ZipCode = "I live in Canada"
AddressBook.Person = "William Yu"
AddressBook.Phone = "555-HELP" Don't worry if you don't understand everything fully, most beginners don't even use UDTs until they're comfortable with the BASIC Language.
|
|
|