Introduction to Variables |
|
Variable Declaration With Type |
Introduction |
As we will see in the next lessons, when a user is asked to provide a value in a program, the value is primarily considered a normal group of characters, also called a string. If you intend to involve that value in an operation that is not meant for a string, you should (usually must) first convert that string to the appropriate value. Fortunately, each data type that we are going to review presents an appropriate and easy mechanism to perform this conversion. |
A natural number is one that contains either only one digit or a combination of digits and no other character, except those added to make it easier to read. Examples of natural numbers are 122 and 2864347. When a natural number is too long, such 3253754343, to make it easier to read, the thousands are separated by a special character. This character depends on the language or group of languages and it is called the thousands separator. For US English, this character is the comma. The thousands separator symbol is used only to make the number easier to read. You will never use it in your code when referring to a number. To support different scenarios, Visual Basic provides different types of natural numbers.
A byte is a group of 8 bits. Since each bit can have a value or either 1 or 0. The total number of possible combinations of 8 bits is 27 + 26 + 25 + 24 + 23 + 22 + 21 + 20 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255. Since all bits can have values of 0 each, a byte can have values from 0 to 255. Therefore, a byte can hold a small natural positive number that ranges from 0 to 255. To declare a variable for a small number, use the Byte keyword. Here is an example: Module Exercise Sub Main() Dim StudentAge As Byte End Sub End Module A Byte variable is initialized with 0. Otherwise, to initialize it, you can assign it a small number from 0 to 255. To convert a value to a Byte value, you can use CByte(). To do this, enter the value or the expression in the parentheses of CByte(). If the conversion is successful, CByte() produces a Byte value. There is no type character for the Byte data type.
If you want to use a very small number but it does not have to be positive, the Visual Basic language provides an alternative. A signed byte is a small number that is between -127 and 128. To declare a variable for such a number, you can use the SByte data type. This can be done as follows: Module Exercise Sub Main() Dim Temperature As SByte End Sub End Module To convert a value to an SByte value, use CSByte(). There is no type character for the SByte data type. An integer is a natural number larger than the Byte. Examples of such ranges are the number of pages of a book, the age of a person. To declare a variable that can hold natural numbers in the range of -32768 to 32767, you can use the Short data type. Here is an example: Module Exercise Sub Main() Dim MusicTracks As Short End Sub End Module By default, a Short variable is initialized with 0. After declaring a Short variable, you can initialize it with the necessary value that must be a relatively small integer from -32768 to 32767. Here is an example: Module Exercise Sub Main() Dim MusicTracks As Short MusicTracks = 16 MsgBox(MusicTracks) End Sub End Module In some cases, the compiler may allocate more memory than the variable needs, beyond the area required by a Short value. To indicate that the number must be treated as a Short and not another type of value, type s or S on the right of the initializing value. Here is an example: Module Exercise Sub Main() Dim MusicTracks As Short MusicTracks = 16S MsgBox("This album contains " & MusicTracks & " tracks.") End Sub End Module This would produce:
To convert a value to a short integer, you can use CShort() by entering the value or the expression in the parentheses of CShort(). If the conversion is successful, CShort() produces a Short value. There is no type character for the Short data type. As mentioned above, a short integer can be either negative or positive. If you want to use a relatively small number that must be positive, you must store it as an unsigned short integer. An unsigned short integer is a natural number between 0 and 65535. To declare a variable that would hold a short positive number, you can use the UShort data type. Here is an example: Module Exercise Sub Main() Dim TotalNumberOfStudents As UShort End Sub End Module There is no type character for the UShort data type. To convert something to an unsigned short integer, put in the parentheses of CUShort().
If you want a variable to hold values larger than the Short data type can accommodate, you can use the Integer data type to declare it. A variable declared with the Integer data type can hold a value between -2,147,483,648 and 2,147,483,647. Here is an example: Module Exercise Sub Main() Dim NumberOfPages As Integer End Sub End Module Alternatively, you can use the % type character to declare an integral variable. Here is an example: Module Exercise Sub Main() Dim NumberOfPages% End Sub End Module To convert a value to an integer, use CInt(): enter the value or the expression in the parentheses of CInt(). If the conversion is successful, CInt() produces an integral value. After declaring an Integer variable, the compiler initializes it with a 0 value. Still, you can initialize it with the necessary value but you have three or four alternatives. To initialize the variable with a regular natural number, you can simply assign it that number. Here is an example: Module Exercise Sub Main() Dim NumberOfPages As Integer NumberOfPages = 846 MsgBox("This book contains " & NumberOfPages & " pages.") End Sub End Module This would produce:
The Visual Basic language considers three types of integer values. Instead of just assigning a regular natural number, to indicate that the value must be considered as an integer, you can enter i or I on the right side of the value. Here is an example: Module Exercise Sub Main() Dim NumberOfPages As Integer NumberOfPages = 846I End Sub End Module The second type of integral number is referred to as hexadecimal. On a surface, it is primarily a different way of representing a number by using a combination of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, A, B, C, D, E, or F. This still allows you to represent any natural number. To initialize an integer variable with a hexadecimal number, start the value with &h or &H. Here is an example: Module Exercise Sub Main() Dim NumberOfStudents As Integer NumberOfStudents = &H4A26EE MsgBox("School Current Enrollment: " & NumberOfStudents & " students.") End Sub End Module This would produce:
Besides the regular natural or the hexadecimal numbers, the third type of value an Integer variable can hold is referred to as octal. This is a technique used to represent a natural number using a combination of 0, 1, 2, 3, 4, 5, 6, and 7. To use such a value, start it with &o or &O (the letter O and not the digit 0). Here is an example: Module Exercise Sub Main() Dim NumberOfStudents As Integer NumberOfStudents = &O4260 MsgBox("School Current Enrollment: " & NumberOfStudents & " students.") End Sub End Module This would produce:
We saw that the Integer data type is used to declare a variable for a large number that can be negative or positive. If you want the number to only be positive, you can declare it as an unsigned integer. An unsigned integer is a number between 0 and 4294967295. Examples are the population of a city, the distance between places of different countries, the number of words of a book. To declare a variable that can a large positive number, use the UInteger data type. Here is an example: Module Exercise Sub Main() Dim Population As UInteger End Sub End Module You can initialize the variable using a positive integer in decimal, hexadecimal, or octal format. To convert a value to an unsigned short integer, use CUInt() by entering the value or the expression in the parentheses. There is no type character for the UInteger data type. A long integer is a very large natural number that is between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. To declare a variable that can hold a very large natural number, use the Long data type. Here is an example: Module Exercise Sub Main() Dim Population As Long End Sub End Module Instead of the AS Long expression, as an alternatively, you can also use the @ symbol as the type character to declare a Long variable. Here is an example: Module Exercise Sub Main() Dim Population@ End Sub End Module To convert a value to a long integer, you can use CLng(). To do this, enter the value or the expression in the parentheses of CLng(). If the conversion is successful, CLng() produces a Long integer value. Like all integers, a Long variable is initialized, by default, with 0. After declaring a Long variable, you can initialize with the necessary natural number. Here is an example: Module Exercise Sub Main() Dim Population@ Population@ = 9793759 MsgBox("Country Population: " & Population) End Sub End Module This would produce:
To indicate that the value must be treated as Long, type l or L on the right side of the number. Here is an example: Module Exercise Sub Main() Dim Population@ Population@ = 9793759L End Sub End Module Because Long is primarily an integral like the Integer data type we reviewed earlier, you can also initialize it using a decimal, a hexadecimal, or an octal value. Here is an example of a variable initialized with a hexadecimal value: Module Exercise Sub Main() Dim Population@ Population = &HFF42AD MsgBox("Country Population: " & Population) End Sub End Module This would produce:
We saw that a long integer can be a very large negative or positive natural number. If you want to store a very large number but the number but be positive, you can consider it as an unsigned long integer. Such a number can be between 0 and 18446744073709551615. To declare a variable that can hold a very large natural positive number, use the ULong data type. Here is an example: Module Exercise Sub Main() Dim DistanceBetweenBothPlanets As ULong End Sub End Module There is no type character for the ULong data type. To convert a value to an unsigned long integer, use CULng().
A real number is one that displays a decimal part. This means that the number can be made of two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel of computers of most regular users:
On both sides of the Decimal Symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines how much precision the number offers.
A decimal number is said to have single precision if it can include a decimal part but the precision of the number is not important. In the Visual Basic language, such a number has a value that can range from -3.402823e38 and -1.401298e-45 if the number is negative, or 1.401298e-45 and 3.402823e38 if the number is positive. To declare a variable that can hold small decimal numbers with no concern for precision, use the Single data type. Here is an example: Module Exercise Sub Main() Dim Distance As Single End Sub End Module Instead of the AS Single expression, you can use the ! symbol as the type character. Here is an example: Module Exercise Sub Main() Dim Distance! End Sub End Module The ! symbol can also be used in other scenarios in the Visual Basic language. Whenever you use it, make sure the word that comes to its right is not the name of a variable. A Single variable is initialized with 0. After declaring a Single variable, you can declare it with the necessary value. Here is an example: Module Exercise Sub Main() Dim Distance! Distance! = 195.408 MsgBox("Distance: " & Distance) End Sub End Module This would produce:
In some cases, the compiler may allocate more memory than necessary for the variable. For example, the above value is more suitable for another type as we will see in the next section. Otherwise, to indicate that the variable must be treated as a decimal number with single-precision, type f or F on the right side of the number. Here is an example: Module Exercise Sub Main() Dim Distance! Distance! = 195.408f End Sub End Module To convert a string to a long integer, call CSng(). Enter the value or the expression in the parentheses of CSng(). If the conversion is successful, CSng() produces a Single value. |
While the Single data type can allow large numbers, it offers less precision. For an even larger number, Visual Basic provides the Double data type. This is used for a variable that would hold numbers that range from 1.79769313486231e308 to 4.94065645841247e324 if the number is negative or from 1.79769313486231E308 to 4.94065645841247E324 if the number is positive. To declare a variable that can store large decimal numbers with a good level of precision, use the Double keyword.
Here is an example of declaring a Double variable: Module Exercise Sub Main() Dim TempFactor As Double End Sub End Module If you want, you can omit the AS Double expression but use the # symbol instead to declare a Double variable. This can be done as follows: Module Exercise Sub Main() Dim TempFactor# End Sub End Module A double-precision variable is initialized with a 0 value. After declaring a Double variable, you can initialize it with the needed value. Here is an example: Module Exercise Sub Main() Dim TempFactor# TempFactor# = 482 MsgBox("Temperature: " & TempFactor & " Degrees") End Sub End Module This would produce:
To indicate that the variable being used must be treated with double precision, enter r or R on its right side. Here is an example: Module Exercise Sub Main() Dim TempFactor# TempFactor# = 482r MsgBox("Temperature: " & TempFactor & " Degrees") End Sub End Module To convert a value to a double-precision number, call CDbl() by entering the value or the expression in the parentheses of CDbl(). If CDbl() succeeds, it produces a Double value.
The decimal data type can be used to declare a variable that would hold significantly large values that can be stored in a combination of 128 bits. You declare such a variable using the Decimal keyword. The values stored in a decimal variable can range from ±1.0 x 10−28 to ±7.9 x 1028 with a precision of 28 to 29 digits. Because of this high level of precision, the Decimal data type is suitable for currency values. Like those of the other numeric types, by default, a variable declared as Decimal is initialized with 0. After declaring a decimal variable, you can initialize it with a natural number. To indicate to the compiler to reserve space enough to store a decimal value, add a d or D to the right side of the value. Here is an example: Module Exercise Sub Main() Dim DistanceBetweenPlanets As Decimal DistanceBetweenPlanets = 592759797549D End Sub End Module To convert a value or an expression to Decimal, you can call CDec().
A character can be a letter, a digit, any readable or non-readable symbol that can be represented. To declare a variable that would hold a character, use the Char data type. Here is an example: Module Exercise Sub Main() Dim Letter As Char End Sub End Module When declaring a Char variable, if you don't initialize it, the compiler does it with an empty character. Otherwise, after declaring a Char variable, you can initialize it with a single character included in double-quotes. Here is an example: Module Exercise Sub Main() Dim Letter As Char Letter = "W" End Sub End Module To indicate that the value of the variable must be treated as Char, when initializing it, you can type c or C on the right side of the double-quoted value. Here is an example: Module Exercise Sub Main() Dim Letter As Char Letter = "W"c End Sub End Module To convert a value to Char, you can call CChar(). A string is an empty text, a letter, a word or a group of words considered "as is". To declare a string variable, you can use the String data type. Here is an example: Module Exercise Sub Main() Dim Sentence As String End Sub End Module If you want, you can replace the AS String expression with the $ symbol when declaring a string variable. This can be done as follows: Module Exercise Sub Main() Dim Sentence$ End Sub End Module After declaring a String variable, by default, the compiler initializes it with an empty string. Otherwise, you can initialize it with a string of your choice. To do this, include the string between double quotes. Here is an example: Module Exercise Sub Main() Dim Sentence$ Sentence$ = "He called me" End Sub End Module If you want to include a double-quote character in the string, you can double it. Here is an example: Module Exercise Sub Main() Dim Sentence$ Sentence$ = "Then she said, ""I don't love you no more."" and I left" MsgBox(Sentence) End Sub End Module This would produce:
To convert a value to a string, call CStr() and enter the value or the expression in its parentheses. If the value is an appropriate date or time, CStr() would produces a string that represents that date or that time value.
A date is a numeric value that represents the number of days that have elapsed since a determined period. A time is a numeric value that represents the number of seconds that have elapsed in a day. To declare a variable that can hold either date values, time values, or both, you can use the Date data type. After the variable has been declared, you will configure it to the appropriate value. Here are two examples: Module Exercise Sub Main() Dim DateOfBirth As Date Dim KickOffTime As Date End Sub End Module As mentioned above, the Date data type is used for both date and time. Like the other values, there are rules you must observe when dealing with date and time values. The rules are defined in the Regional Settings Properties of the Control Panel of the computer on which the application is run. The rules for the dates are defined in the Date property page:
The rules for the time values are defined in the Time property page:
When using date and time values in your applications, you should not change these rules because the application will refer to them when it is installed in someone else's computer. By default, a Date variable is initialized with January 1st, 0001 at midnight as the starting value. After declaring a Date variable, you can initialize it with an appropriate date or time or date and time value. The value can be included in double-quotes. Here is an example: Module Exercise Sub Main() Dim DateOfBirth As Date DateOfBirth = "08/14/1982" MsgBox("Date of Birth: " & DateOfBirth) End Sub End Module This would produce:
If you intend to use only a date value for a Date variable, its corresponding time part would be set to midnight of the same date. Based on this, the above program would produce: 8/14/1982 12:00:00 AM If you intend to use only a time value for your Date variable, the date part of the variable would be set to January 1st, 0001. A Date value can also be included between two # signs. Here is an example: Module Exercise Sub Main() Dim DateOfBirth As Date Dim KickOffTime As Date DateOfBirth = "08/14/1982" KickOffTime = #6:45:00 PM# MsgBox("Date of Birth: " & DateOfBirth) MsgBox("Kick off Time: " & KickOffTime) End Sub End Module To convert a value to a date or a time value, write an appropriate date or a recognizable time in the parentheses of CDate(). If the value is appropriate, CDate() produces a Date value.
An Object can be any type of data that you want to use in your program. In most cases, but sparingly, it can be used to declare a variable of any type. Here are examples: Module Exercise Sub Main() Dim CountryName As Object Dim NumberOfPages As Object Dim UnitPrice As Object CountryName = "Australia" NumberOfPages = 744 UnitPrice = 248.95 MsgBox("Country Name: " & CountryName) MsgBox("Number of Pages: " & NumberOfPages) MsgBox("Unit Price: " & UnitPrice) End Sub End Module If you do not specify a data type or cannot figure out what data type you want to use, you can use the Object data type. As you can see from the result of the above program, the vbc compiler knows how to convert the value of any Object variable to the appropriate type. On the other hand, to convert a value or an expression to the Object type, you can use CObj().
|
|
||
Previous | Copyright © 2008-2016, FunctionX, Inc. | Next |
|