Variables In Programming
What is a Variable?
There are different ways to define variable, let see few:
• Donald Knuth: – A quantity that may possess different values as a program is being executed.
• Mehran Sahami: – A box in which we stuff things – i.e. a box with variable content.
• Wikipedia: – User defined keyword that is linked to a value stored in computer’s memory (runtime).
•A symbol or name that stands for a value.
• A variable is a value that can change.
• Variables provide temporary storage for information that will be needed during the lifespan of the computer program (or application).
Don’t let us pay attention to how it was defined, let us just pick the key point and concept which is that “variable store value for the period of running of the program”
z = x + y
• This is an example of programming expression.
• x, y and z are variables.
• Variables can represent numeric values, characters, character strings, or memory addresses.
In a program every, variable has:
– NAME (Identifier) e. g x, y and z
– DATA Type (nature of data store in the variable)
– VALUE (this is the content store in the variable)
Loosely Typed / Strictly Typed Languages
If the following works:
x = 10;
x = “Fred”;
then it’s loosely typed (two different types of data in the same variable and scope).
Strongly Typed Language: Languages where variables must be declared to contain a specific type of data.
String myString = “Peter”;
then your language is strictly typed, variable “myString” is explicitly declared to contain only string data. Then it’s loosely typed .
Types of Variable
• there are two types of variables:
– Local variable
– Global variable
Types of Variable
• Local variables are those that are in scope within a specific part of the program (function, procedure, method, or subroutine, depending on the programming language employed).
• Global variables are those that are in scope for the duration of the programs execution. They can be accessed by any part of the program, and are readwrite for all statements that access them.
Rules in Naming a Variable
• There a certain rules in naming variables (identifier).
• They are: – It should use only alphabets, number and underscore ( _ )
– It should not begin with a number and must have at least one alphabet.
– It should not be a reserved word.
• Examples of reserved word:
Main, log, if do continue, short, else, return, const, int, double, break, void, while, char e.t.c