music
OSdata.com: programming text book 

OSdata.com

program variables

summary

    Variables are a place where a program temporarily stores information.

free computer programming text book project

table of contents
If you like the idea of this project,
then please donate some money.
more information on donating

Google

program variables

    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 Plauger’s The Elements of Programming Style] claims that variable names should be chosen meaningfully, doesn’t it then follow that variables whose names are small essays on their use are even better? Isn’t MaximumValueUntilOverflow a better name than maxval? I don’t think so.” —Rob Pike, Notes on Programming in C, February 21, 1989

variable identifiers

    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 Lispanything 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
Forthanything 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$]*
Lispanything 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]*

Pascal

    Variables may have any valid identifier name in Pascal.

explicit and implied declaration

    Some languages require that variables be explicitly declared, while other languages allow an implicit declaration.

Pascal

    Variables must be explicitly declared in Pascal.

FORTRAN

    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-Europe’s 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-Europe’s Ada Reference Manual: Introduction See legal information

declaration location

    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).

Pascal

    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.

declaration format

    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 needn’t 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, it’s harder to see what’s 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

Pascal

    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;

type

    Programming laguages typically have data types, which may be determined explicitly or implicitly.

integer type

    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.

Pascal

    In Pascal the integer type is declared with the reserved word intger.

var    Age: Integer;

floating point type

    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.

Pascal

    In Pascal the floating point type is declared with the reserved word real.

var    FinalAverage: real;

floating point notation

    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

character type

    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.

Pascal

    In Pascal the character type is declared with the reserved word char.

var    MiddleIntial: char;

multiple definitions

    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.

Pascal

    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, don’t call its cousin lowestaddress.” —Rob Pike, Notes on Programming in C, February 21, 1989

Stanford C essentials

    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.

Variables

    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.

end of Stanford C essentials

Stanford Perl essentials

    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.

2. Syntax And Variables

    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";
    }

What’s With This ‘$’ Stuff?

    Larry Wall, Perl’s 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, it’s 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”. (It’s 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.

end of Stanford Perl essentials

Ruby

    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 it’s 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 ($).

other

   “One man’s constant is another man’s variable.” —Alan Perlis, Epigrams on Programming, ACM’s 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, ACM’s 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, ACM’s SIGPLAN Notices Volume 17, No. 9, September 1982, pages 7-13


free music player coding example

    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

view text book
HTML file

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
previous page next page

free computer programming text book project

Building 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,
then please donate some money.

send donations to:
Milo
PO Box 1361
Tustin, California 92781

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)

more information on donating

Some or all of the material on this web page appears in the
free downloadable college text book on computer programming.


Google


Made with Macintosh

    This web site handcrafted on Macintosh computers using Tom Bender’s Tex-Edit Plus and served using FreeBSD .

Viewable With Any Browser


    †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
previous page next page