music |
OSdata.com |
program variables
summary
Variables are a place where a program temporarily stores information.
free computer programming text book projecttable of contents
|
music |
OSdata.com |
Variables are a place where a program temporarily stores information.
free computer programming text book projecttable of contents
|
Variables are a place where a program temporarily stores information. They are kind of like a container holding program information.
If the book [Kernighan and Plaugers The Elements of Programming Style] claims that variable names should be chosen meaningfully, doesnt it then follow that variables whose names are small essays on their use are even better? Isnt MaximumValueUntilOverflow a better name than maxval? I dont think so. Rob Pike, Notes on Programming in C, February 21, 1989
Variables are named with identifiers. In most languages variables may be given any valid identifer name.
Quick summary of the rules for building valid variable identifiers in several major languages, using regular expressions:
Ada | [a-zA-Z](_?[a-zA-Z0-9])* |
---|---|
ALGOL-68 | [a-z][a-z0-9 ]* |
Awk | [_a-zA-Z][_a-zA-Z0-9]* |
B | [_a-zA-Z][_a-zA-Z0-9]* |
BourneShell | [_a-zA-Z0-9]+ |
C | [_a-zA-Z][_a-zA-Z0-9]* |
C# | [_a-zA-Z][_a-zA-Z0-9]* |
C++ | [_a-zA-Z][_a-zA-Z0-9]* |
COBOL | [a-zA-Z][a-zA-Z0-9-]* 30 character maximum |
Classic REXX | [a-zA-Z!?@#][a-zA-Z0-9!?@#]* |
Common Lisp | anything without a space and is not a number |
E | [_a-zA-Z][_a-zA-Z0-9]* |
Eiffel | [a-zA-Z][_a-zA-Z0-9]* |
F# | [_a-zA-Z][_a-zA-Z0-9']* |
FORTRAN | [A-Z][A-Z0-9]* maximum of six characters |
Forth | anything without a space and is not a number |
GNU-bc | [a-z][a-z0-9_]* |
Haskell | [_a-z][_a-zA-Z0-9']* |
Java | [_a-zA-Z$][_a-zA-Z0-9$]* |
JavaScript | [_a-zA-Z$][_a-zA-Z0-9$]* |
Lisp | anything without a space and is not a number |
Maple | [_a-zA-Z][_a-zA-Z0-9]* |
Mathematica | [a-zA-Z][a-zA-Z0-9]* |
Matlab | [a-zA-Z][_a-zA-Z0-9]* |
Mercury | [_a-z][_a-zA-Z0-9']* |
merd | [_a-z][_a-zA-Z0-9]*[!?']* |
Modula-3 | [a-zA-Z][_a-zA-Z0-9]* |
MUMPS | [a-zA-Z%][a-zA-Z0-9]* |
OCaml | [_a-z][_a-zA-Z0-9']* |
Pascal | [a-zA-Z][a-zA-Z0-9]* |
Perl | [_a-zA-Z0-9]+ |
Perl6 | [_a-zA-Z0-9]+ |
PHP | [_a-zA-Z][_a-zA-Z0-9]* |
PL/I | [a-zA-Z][a-zA-Z0-9]* |
Pliant | [_a-zA-Z][_a-zA-Z0-9]* or '[^']*' |
Prolog | [_A-Z][_a-zA-Z0-9]* |
Python | [_a-zA-Z][_a-zA-Z0-9]* |
Rebol | [_a-zA-Z?!.'+*&|=~-][_a-zA-Z0-9?!.'+*&|=~-]* or [^0-9[](){}":;/][^ \n\t[](){}":;/]* |
Ruby | [_a-z][_a-zA-Z0-9]* |
Scheme | [_a-zA-Z!0&*/:<=>?^][_a-zA-Z!0&*/:<=>?^0-9.+-]* |
SmallTalk | [a-zA-Z][a-zA-Z0-9]* |
SML | [_a-z][_a-zA-Z0-9']* |
Tcl | [_a-zA-Z][_a-zA-Z0-9]* |
Variables may have any valid identifier name in Pascal.
Some languages require that variables be explicitly declared, while other languages allow an implicit declaration.
Variables must be explicitly declared in Pascal.
Undeclared variables that start with the letters I through N, inclusive, (short for INteger) are assumed to be integers, while all other undeclared variables are assumed to be floating point.
Whether or not your programming language requires explicit declaration of all variables or not, you really want to do it.
Declaring all variables will help identify programming errors where the only mistake was mistyping the name of a variable (that includes changing case for languages that are case-sensitive).
The following comment from Ada-Europes Ada Reference Manual discusses decisions made for the Ada programming language (but these principles apply to all languages):
Design Goals Ada was originally designed with three overriding concerns: program reliability and maintenance, programming as a human activity, and efficiency. The need for languages that promote reliability and simplify maintenance is well established. Hence emphasis was placed on program readability over ease of writing. For example, the rules of the language require that program variables be explicitly declared and that their type be specified. Since the type of a variable is invariant, compilers can ensure that operations on variables are compatible with the properties intended for objects of the type. Furthermore, error-prone notations have been avoided, and the syntax of the language avoids the use of encoded forms in favor of more English-like constructs. Finally, the language offers support for separate compilation of program units in a way that facilitates program development and maintenance, and which provides the same degree of checking between units as within a unit. :Ada-Europes Ada Reference Manual: Introduction See legal information
Some languages require that variables be declared in a specific portion of the program, while others allow variable declarations to be scattered through a program (but usually still must be before first actual use).
In Pascal variables must be declared in the declaration part, which comes immediately before the statement part.
program SimpleProgram (output);
var Age: Integer;
begin
Age := 21;
write ('Susan is ');
write (Age);
writeln (' years old.')
end.
Note that outputting a variable involves giving the name of the variable without any apostrophes (quotation marks).
The output of this program would be:
Susan is 21 years old.
end.
The format for a declaration varies by programming language.
Ah, variable names.ÊLength is not a virtue in a name; clarity of expression is.ÊA global variable rarely used may deserve a long name, maxphysaddr say.ÊAn array index used on every line of a loop neednt be named any more elaborately than i.Ê Saying index or elementnumber is more to type (or calls upon your text editor) and obscures the details of the computation.ÊWhen the variable names are huge, its harder to see whats going on.ÊThis is partly a typographic issue; consider
for(i=0 to 100)
array[i]=0 ;
vs.
for(elementnumber=0 to 100)
array[elementnumber]=0;
The problem gets worse fast with real examples.ÊIndices are just notation, so treat them as such. Rob Pike, Notes on Programming in C, February 21, 1989
In Pascal the order of the parts of a declaration are: the reserved word var, the name of the variable, a colon character ( : ), the type of the variable, and the semicolon terminator.
var Age: Integer;
Programming laguages typically have data types, which may be determined explicitly or implicitly.
Most programs have an integer type. This is a computer representation of the mathematical integers (counting numbers, zero, and negative integers).
Unlike mathematical integers, computer integers have a range, a maximum (largest) and minimum (smallest negative) number.
Note that negative integers are indicated with a negative sign (such as -3), while positive integers are indicated by the lack of a sign (such as 3).
Unlike normal written numbers, you leave out the commas when writing numbers in a computer program. The number 1,000,000 (one million) is written 1000000. Adding the commas will confuse your compiler.
In Pascal the integer type is declared with the reserved word intger.
var Age: Integer;
Most programs have a floating point type. This is a computer representation of the mathematical real numbers.
Unlike mathematical real numbers, computer floating point numbers have a range, a maximum (largest) and minimum (smallest negative) number.
In Pascal the floating point type is declared with the reserved word real.
var FinalAverage: real;
The floating point number is often input and output in a floating point notation, a variation of scientific notation.
The floating point number is often input and output in a floating point notation, a variation of scientific notation.
The format (from left to right) is a sign for the mantissa, the mantiassa (which may have a decimal point and both an integer and fractional part), the letter E, a positive or negative sign for the exponent, and the exponent (which may have a decimal point and both an integer and fractional part).
In the vast majority of languages the fractional part is optional, but if there is a fractional part then there must be at least one digit to the left of the decimal point (although it can be a zero).
In many languages it is possible to leave off the exponent part.
Examples:
notation | number |
---|---|
0.0 | 0 |
0.5 | 0.5 (half) |
-1.23 | -1.23 negative |
5E+7 | 50000000 50,000,000 |
5.5E+7 | 55000000 55,000,000 |
5.5E-04 | 0.00055 |
-0.000255E+05 | 25.5 |
The character type is used to store printable characters (although it may include unprintable characters as well). The printable characters are the upper and lower case letters, digits, space character, and punctuation marks.
In Pascal the character type is declared with the reserved word char.
var MiddleIntial: char;
In almost all languages each variable may be declared on a separate line.
In many languages it is possible to declare several variables of the same type in a single declaration.
In Pascal it is possible to declare multiple variables in the same declaration as long as they all share the exact same type. In this case the variable identifier names will be separated by a comma.
var RunningSubTotal, FinalTotal: integer;
As in all other aspects of readable programming, consistency is important in naming.ÊIf you call one variable maxphysaddr, dont call its cousin lowestaddress. Rob Pike, Notes on Programming in C, February 21, 1989
Stanford CS Education Library This [the following section until marked as end of Stanford University items] is document #101, Essential C, in the Stanford CS Education Library. This and other educational materials are available for free at http://cslibrary.stanford.edu/. This article is free to be used, reproduced, excerpted, retransmitted, or sold so long as this notice is clearly reproduced at its beginning. Copyright 1996-2003, Nick Parlante, nick.parlante@cs.stanford.edu.
As in most languages, a variable declaration reserves and names an area in memory at run time to hold a value of particular type. Syntactically, C puts the type first followed by the name of the variable. The following declares an int variable named num and the 2nd line stores the value 42 into num.
int num;
num = 42;
A variable corresponds to an area of memory which can store a value of the given type. Making a drawing is an excellent way to think about the variables in a program. Draw each variable as box with the current value inside the box. This may seem like a beginner technique, but when I'm buried in some horribly complex programming problem, I invariably resort to making a drawing to help think the problem through.
Variables, such as num, do not have their memory cleared or set in any way when they are allocated at run time. Variables start with random values, and it is up to the program to set them to something sensible before depending on their values.
Names in C are case sensitive so x and X refer to different variables. Names can contain digits and underscores (_), but may not begin with a digit. Multiple variables can be declared after the type by separating them with commas. C is a classical compile time language -- the names of the variables, their types, and their implementations are all flushed out by the compiler at compile time (as opposed to figuring such details out at run time like an interpreter).
float x, y, z, X;
Stanford CS Education Library This [the above section] is document #101, Essential C, in the Stanford CS Education Library. This and other educational materials are available for free at http://cslibrary.stanford.edu/. This article is free to be used, reproduced, excerpted, retransmitted, or sold so long as this notice is clearly reproduced at its beginning. Copyright 1996-2003, Nick Parlante, nick.parlante@cs.stanford.edu.
This [the following section until marked as end of Stanford University items] is document #108 [Essential Perl] in the Stanford CS Education Library --see http://cslibrary.stanford.edu/108/. This document is free to be used, reproduced, or sold so long as this paragraph and the copyright are clearly. Copyright 2000-2002, Nick Parlante, nick.parlante@cs.stanford.edu.
The simplest Perl variables are scalar variables which hold a single string or number. Scalar variable names begin with a dollar sign ($) such as $sum or $greeting. Scalar and other variables do not need to be pre-declared -- using a variable automatically declares it as a global variable. Variable names and other identifiers are composed of letters, digits, and underscores (_) and are case sensitive. Comments begin with a # and extend to the end of the line.
$x = 2; ## scalar var $x set to the number 2
$greeting = "hello"; ## scalar var $greeting set to the string "hello"
A variable that has not been given a value has the special value undef which can be detected using the defined operator. Undef looks like 0 when used as a number, or the empty string "" when used as a string, although a well written program probably should not depend on undef in that way. When Perl is run with warnings enabled (the -w flag), using an undef variable prints a warning.
if (!defined($binky)) {
print "the variable 'binky' has not been given a value!\n";
}
Larry Wall, Perls creator, has a background in linguistics which explains a few things about Perl. I saw a Larry Wall talk where he gave a sort of explanation for the $ syntax in Perl: In human languages, its intuitive for each part of speech to have its own sound pattern. So for example, a baby might learn that English nouns end in -y -- mommy, daddy, doggy. (Its natural for a baby to over generalize the rule to get made up words like bikey and blanky.) In some small way, Perl tries to capture the different-signature-for-different-role pattern in its syntax -- all scalar expressions look alike since they all start with $.
This [the above section] is document #108 [Essential Perl] in the Stanford CS Education Library --see http://cslibrary.stanford.edu/108/. This document is free to be used, reproduced, or sold so long as this paragraph and the copyright are clearly. Copyright 2000-2002, Nick Parlante, nick.parlante@cs.stanford.edu.
There are no data types in Ruby. Instead there are objects, as Ruby is exclusively an Object Oriented Programming language. Ruby does not have variable declarations nor static types.
Ruby uses duck typing. That is, Ruby analyzes the context and decides on the type accordingly.
This apporach is named for the famous phrase If it walks like a duck, fquacks like a duck, flies like a duck, and swims like a duck, then its probably a duck.
Local variables must start with a lowercase letter or an underscore character (_).
Instance variables must start with a single at sign (@).
Class variables must start with two at signs (@@).
Global varaiables must start with a dollar sign ($).
One mans constant is another mans variable. Alan Perlis, Epigrams on Programming, ACMs SIGPLAN Notices Volume 17, No. 9, September 1982, pages 7-13
47. As Will Rogers would have said, There is no such thing as a free variable. Alan Perlis, Epigrams on Programming, ACMs SIGPLAN Notices Volume 17, No. 9, September 1982, pages 7-13
66. Making something variable is easy. Controlling duration of constancy is the trick. Alan Perlis, Epigrams on Programming, ACMs SIGPLAN Notices Volume 17, No. 9, September 1982, pages 7-13
Coding example: I am making heavily documented and explained open source code for a method to play music for free almost any song, no subscription fees, no download costs, no advertisements, all completely legal. This is done by building a front-end to YouTube (which checks the copyright permissions for you).
View music player in action: www.musicinpublic.com/.
Create your own copy from the original source code/ (presented for learning programming).
return to table of contents
free downloadable college text book
Because I no longer have the computer and software to make PDFs, the book is available as an HTML file, which you can convert into a PDF.
previous page | next page |
Tweets by @osdata |
free computer programming text book projectBuilding a free downloadable text book on computer programming for university, college, community college, and high school classes in computer programming. If you like the idea of this project, Supporting the entire project: If you have a business or organization that can support the entire cost of this project, please contact Pr Ntr Kmt (my church) free downloadable college text book on computer programming. |
This web site handcrafted on Macintosh computers using Tom Benders Tex-Edit Plus and served using FreeBSD .
UNIX used as a generic term unless specifically used as a trademark (such as in the phrase UNIX certified). UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company Ltd.
Names and logos of various OSs are trademarks of their respective owners.
Copyright © 2010, 2011 Milo
Created: October 30, 2010
Last Updated: March 18, 2011
return to table of contents
free downloadable college text book
previous page | next page |