Vous êtes sur la page 1sur 32

Chapter 4 Constants & Variables

Every programming language has some elements

that you must know by heart - its like knowing a core vocabulary in a language. Sure you could look a word up in a dictionary; but things go a lot faster knowing a core vocabulary by heart. It used to be one could commit the whole of a language like C or FORTRAN and all their APIs to memory; but with Visual Basic's large syntax and huge API including now more of the native Windows SDK, that is a superhuman task.

So here are four essential parts of Visual Basic syntax to know and understand very well : 1) all the variable types (integer, string,etc.) and when to use them; 2) the naming and scope conventions for variables, 3)all the commands in Visual Basic's syntax that control flow of operations(for, if - then, etc.) 4)how parameters are passed and treated when used in subroutines.

Visual Basic Variables


All programs manipulate values contained in

variables.Variables are stored temporarily in memory and/or permanently on hard disk. variable is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value. For storage efficiency and runtime speed, different types of variables can be used in a Visual Basic program. There are 12 different variable types which can be grouped into two major categories - numeric and other special types.

In addition, using the Type statement you can

create your own variable type. But here are all the Visual Basic variable types defined using VB syntax (remember, a comment in Visual Basic is any line beginning with an apostrophe, or all the text after an apostrophe):

Numeric types
Dim A as Byte
'declare A as 1 byte numeric value ranging from 0

to 255. Used in bit/byte manipulations.

Dim A as Integer

'declares A" as a numeric variable of 2 bytes whose values can range between -32768 to 32767 ' use Integers for loop variables, counters and small table indexes.

Dim A as Long

'declares A" as a whole number of 4 bytes with range between -2,147,483,648 to 2,147,483,647 ' use Longs for indexes into large tables, file i/o, and other VB counters;

Dim A as Currency

'declares A" as a numeric variable of 10 bytes with high calculation accuracy ' which ranges from 922,337,203,685,477.5808 to 922,337,203,685,477.5807. ' Use this data type for calculations involving money and fixed decimal point accuracy. ' Currency calculations are about as fast as longs.

Dim A as Single
'declares A" as a single precision floating point

variable. ' Use Double rather than Single except where demanded by VB/Windows API; ' Double is much more accurate and even runs about 10-20% faster than Single.

Dim A as Double
'declares A" as a double precision floating point

variable of 8 bytes which can range from ' -1.79769313486232E308 to 4.94065645841247E-324 for negative values; ' 4.94065645841247E-324 to 1.79769313486232E308 for positive values. ' Use when a numeric value can have several decimal places or range to extreme sizes.

Other Types
Dim A as Date
'declares A as a Date value which stores both date

and time in one 8 byte variable.

Dim A as String
' declares A" as a dynamic string of varying length.

Strings are used everywhere in VB; ' there is a fixed string type,

Dim A as Variant
'declares A as a Variant variable of minimum 16

bytes in length. Variants, as the name implies, ' can store date or numeric or string or object/reference values. It is the default variable type. ' The trade-off with Variants is their flexibility/ease of use versus storage size cost and speed ' disadvantage, about 3 times slower than integer or longs, 4-6 times slower than doubles. Variants ' also have the nagging ability to camouflage bugs in coding. Use carefully.

Dim A as string
'declares A as a string variable of 2 bytes ,which

values as false or true

Main content
Naming Conventions in Visual Basic

Introduction to Variables, Constants and Data

Types Variables Constants Data Types

example

Naming Conventions in VB
While you are writing Visual Basic code, you

declare and name many elements (Sub and Function procedures, variables, constants, and so on). The names of the procedures, variables, and constants that you declare in your Visual Basic code must follow these guidelines:

They must begin with a letter.

They can't contain embedded periods or type-

declaration characters (special characters that specify a data type. They can be no longer than 255 characters. The names of controls, forms, classes, and modules must not exceed 40 characters. They can't be the same as restricted keywords.

Variables
Variables are storage locations in memory that are

used for a wide variety of data. The variable receives a variable name from the programmer, which allows access to the memory location. The programmer does not have to know the physical memory address of information to retrieve and manipulate it. The variable name is used as a reference to the physical address and reduces the work of the programmer

Variables are Temporary


They exist just as long as they are needed and

are then disposed of. Another analogy is that variables are like numbers in a calculator. As soon as you hit the clear or power off buttons, the display numbers are lost.

assign the result to a variable:

ApplesSold = 10

' The value 10 is passed to

the variable. ApplesSold = ApplesSold + 1 ' The variable is incremented. Note that the equal sign in this example is an assignment operator, not an equality operator; the value (10) is being assigned to the variable (ApplesSold)

Declaring Variables
When the programmer requires a variable, Visual

Basic allows two different ways of declaring them

Implicit Declaration
The first method is called implicit variable

declaration. This method enables a programmer to use a variable any time he or she requires one. The programmer just has to type a new variable name into the source code and the variable is automatically created by VB. The following line of code uses implicit variable declaration: x = Hello In this code sample, the x contains the String value Hello. Visual Basic automatically created x and selected a default data type for the variable.

Explicit Declaration
The second method of using variables is called

explicit variable declaration. To use this method, the programmer must first name the variable and describe what type of information will be contained within the variable. The following line of code is an example of explicit variable declaration: Dim x As String
In this code sample, before the programmer can use x and assign a value to it, the x is declared. The Dim statement is used to dimension a variable called x. The variable will hold String information.

Explicit declarations have the following three

parts. The first word is a keyword that determines the scope or lifetime of the variable. The second part is the variable name that will be used in the source code. The third part is the data type of the variable that tells the computer how much memory is required to hold the information.

Dim variablename [As


type]

tips
However, the implicit variable declaration is not a

good practice, because you can misspell the variable name later in your code, and that can cause strange results when it is running. This is because when you misspell for example the "name" variable to "nime" the programe will automatically create a new variable called "nime". To prevent your code from doing this you can use the Option Explicit statement. When you use this statement you will have to declare all your variables with the dim, public or private statement. Put the Option Explicit statement on the top of your code. Like this:

example
Option Explicit Private Sub Command1_Click() Dim a%, b%, c% a=4 b=7 c=a+b c1=a*d Label1.Caption = c Label2.Caption = c1 End Sub

What is will happen when click command1?

Understanding the Scope of Variables


we have seen that a variable declaration contains

the name of the variable as well as the data type. Another important aspect of a variable declaration is the scope. The scope of a variable determines where in the application that variable can be referenced. This allows only certain parts of the program to have access to information and provides security for the data.

example
Private Sub Command1_Click()

Dim a%, b%, c% a=4 b=7 c=a+b Label1.Caption = c End Sub Private Sub Command2_Click() Label2 = c End Sub

What is will happen when click command1?

What is will happen when click command2?

cause
The scope of a variable defines which parts of

your code are aware of its existence. When you declare a variable within a procedure, only code within that procedure can access or change the value of that variable; it has a scope that is local to that procedure. Sometimes, however, you need to use a variable with a broader scope, such as one whose value is available to all the procedures within the same module, or even to all the procedures in your entire application. Visual Basic allows you to specify the scope of a variable when you declare it.

Converting Between DataTypes


Very often, you need to use different data types

together in the same expression. Visual Basic can often perform data-type conversion automatically, and you, as the programmer, need not concern yourself with what goes on behind the scenes in these cases. At other times, however, you will need to convert a variable to another data type before you use it. This is necessary when you want to pass a variable as an argument to a function or procedure, and the procedure is expecting a parameter of a different data type.

Automatic Type Conversion


Visual Basic is very versatile in converting

between data types, especially between String and other types. In many cases, you can just let Visual Basic do an internal conversion for you in numeric and String expressions without having to use any special conversion functions or other precautions.

Automatic Conversion Between Numeric Values


Visual Basic is very versatile in converting

between data types, especially between String and other types. In many cases, you can just let Visual Basic do an internal conversion for you in numeric and String expressions without having to useSub any special conversion or other Private Form_Click() Private functions Sub Form_Click() Dim a%, b% Dim a%, b%,c% precautions.
a=4 b=7 c=a/b Print c End Sub a=4 b=7 c=a/b Print c End Sub

Dim Value

' declare Value as variant(default)

Value = 18 ' set value string18 Value = Value 15 ' convert string to integerresult? Value = U & Value ' convert integer to string result?

Constants
The declaration of a constant variable begins with

the letters Const, not the letters Dim You must assign the value to be contained in the constant on the same line as the definition of the constant. You cannot attempt to change the value in the constant variable anywhere in the program. If you attempt this, you will produce a compiler error The letter c often is placed before the prefix of the constant variable name to identify throughout the program that it is a constant variable and cannot be changed Other than the letter c constant variable names are formed using the same rules and techniques as nonconstant names

Vous aimerez peut-être aussi