music
OSdata.com: programming text book 

OSdata.com

assignment

summary

    This subchapter looks at assignment.

    Assignment statements and/or assignment operators are used to assign or modify the value of variables. Assignment statements often include arithmetic or computation expressions.

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

assignment

    Assignment statements and/or assignment operators are used to assign or modify the value of variables. Assignment statements often include arithmetic or computation expressions.

basic assignment

    The assignment statement transfers data from a source to a destination. The destination is usually a variable. In most languages the source can be a constant, variable, function, or expression.

    The most basic version is assigning a constant number to a variable. In the following examples we will assign the value of zero (0) to a variable named x:

Ada
        x := 0;

ALGOL
        x := 0

APL
        X←0

BASIC
        LET X = 0

C
        x = 0;

COBOL
        MOVE ZERO TO X.
        -OR-
        MOVE 0 TO X.

FORTRAN
        X = 0

LISP
        (SETQ X 0)

Pascal
        x := 0;

PHP
        $X := 0;

PL/I
        X = 0;

C

    Note that unlike most programming languages, C does not have an assignment statement, but rather has an assignment operator. This allows assignment to be compacted into other programming constructs, which can lead to confusion.

    One classic C mistake is using the assignment operator rather than the equality test in an if statement:

if (x == 0) dosomething();   /* tests to see if x is equal to zero
if (x = 0) dosomething();   /* assigns zero to x and tests to see if x is zero

    This feature can be used to make very terse (and confusing) code:

while (*p++ = *q++) ;

    The above loop copies copies data from one string or block of data to another until a zero is encountered. See while loops.

    Brian Kernighan and Dennis Ritchie (the original creators of C) in their famous book The C Programming Language “recommend writing only one statement per line, and using blanks around operators to clarify grouping.”

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.

Assignment Operator =

    The assignment operator is the single equals sign (=).

    i = 6;
    i = i + 1;

    The assignment operator copies the value from its right hand side to the variable on its left hand side. The assignment also acts as an expression which returns the newly assigned value. Some programmers will use that feature to write things like the following.

    y = (x = 2 * x);    // double x, and also put x's new value in y

Type Combination and Promotion

    The integral types may be mixed together in arithmetic expressions since they are all basically just integers with variation in their width. For example, char and int can be combined in arithmetic expressions such as ('b' + 5). How does the compiler deal with the different widths present in such an expression? In such a case, the compiler “promotes” the smaller type (char) to be the same size as the larger type (int) before combining the values. Promotions are determined at compile time based purely on the types of the values in the expressions. Promotions do not lose information -- they always convert from a type to compatible, larger type to avoid losing information.

Pitfall -- int Overflow

    I once had a piece of code which tried to compute the number of bytes in a buffer with the expression (k * 1024) where k was an int representing the number of kilobytes I wanted. Unfortunately this was on a machine where int happened to be 16 bits. Since k and 1024 were both int, there was no promotion. For values of k >= 32, the product was too big to fit in the 16 bit int resulting in an overflow. The compiler can do whatever it wants in overflow situations -- typically the high order bits just vanish. One way to fix the code was to rewrite it as (k * 1024L) -- the long constant forced the promotion of the int. This was not a fun bug to track down -- the expression sure looked reasonable in the source code. Only stepping past the key line in the debugger showed the overflow problem. “Professional Programmer’s Language.” This example also demonstrates the way that C only promotes based on the types in an expression. The compiler does not consider the values 32 or 1024 to realize that the operation will overflow (in general, the values don’t exist until run time anyway). The compiler just looks at the compile time types, int and int in this case, and thinks everything is fine.

Truncation

    The opposite of promotion, truncation moves a value from a type to a smaller type. In that case, the compiler just drops the extra bits. It may or may not generate a compile time warning of the loss of information. Assigning from an integer to a smaller integer (e.g.. long to int, or int to char) drops the most significant bits. Assigning from a floating point type to an integer drops the fractional part of the number.

    char ch;
    int i;

    i = 321;
    ch = i;    // truncation of an int value to fit in a char
    // ch is now 65

    The assignment will drop the upper bits of the int 321. The lower 8 bits of the number 321 represents the number 65 (321 - 256). So the value of ch will be (char)65 which happens to be ‘A’.

    The assignment of a floating point type to an integer type will drop the fractional part of the number. The following code will set i to the value 3. This happens when assigning a floating point number to an integer or passing a floating point number to a function which takes an integer.

    double pi;
    int i;
    pi = 3.14159;
    i = pi; // truncation of a double to fit in an int
    // i is now 3

Pitfall -- int vs. float Arithmetic

    Here’s an example of the sort of code where int vs. float arithmetic can cause problems. Suppose the following code is supposed to scale a homework score in the range 0..20 to be in the range 0..100.

    {
       int score;
    ...// suppose score gets set in the range 0..20 somehow
       score = (score / 20) * 100;    // NO -- score/20 truncates to 0
    ...

    Unfortunately, score will almost always be set to 0 for this code because the integer division in the expression (score/20) will be 0 for every value of score less than 20. The fix is to force the quotient to be computed as a floating point number…

score = ((double)score / 20) * 100;    // OK -- floating point division from cast
score = (score / 20.0) * 100;          // OK -- floating point division from 20.0
score = (int)(score / 20.0) * 100;     // NO -- the (int) truncates the floating
                                       // quotient back to 0

Mathematical Operators

    C includes the usual binary and unary arithmetic operators. See the appendix for the table of precedence. [Found in this book in the subchapter on order of precedence] Personally, I just use parenthesis liberally to avoid any bugs due to a misunderstanding of precedence. The operators are sensitive to the type of the operands. So division (/) with two integer arguments will do integer division. If either argument is a float, it does floating point division. So (6/4) evaluates to 1 while (6/4.0) evaluates to 1.5 -- the 6 is promoted to 6.0 before the division.

      +    Addition

      -    Subtraction

      /    Division

      *    Multiplication

      %    Remainder (mod)

Other Assignment Operators

    In addition to the plain = operator, C includes many shorthand operators which represents variations on the basic =. For example “+=” adds the right hand side to the left hand side. x = x + 10; can be reduced to x += 10;. This is most useful if x is a long expression such as the following, and in some cases it may run a little faster.

person->relatives.mom.numChildren += 2;    // increase children by 2

    Here’s the list of assignment shorthand operators…

+=, -=      Increment or decrement by RHS
*=, /=      Multiply or divide by RHS
%=      Mod by RHS
>>=      Bitwise right shift by RHS (divide by power of 2)
<<=      Bitwise left shift RHS (multiply by power of 2)
&=, |=, ^=      Bitwise and, or, xor by RHS

    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

Ada

    “24 An assignment statement changes the value of a variable.” —:Ada-Europe’s Ada Reference Manual: Introduction: Language Summary See legal information

        target := source;

    Ada distinguishes between an assignment and an assignment statement.

    In Ada assignment is indicated by the character pair colon and equal := and an assignment statement is terminated with a semicolon ;.

    The EBNF definition of an Ada assignment statement is:

assignment_statement ::= variable_name := expression;

    Only one variable may be on the left side of an assignment statement. The value assigned must be the same type as the variable and within the legal range for that variable.

JOVIAL

    The following material is from the unclassified Computer Programming Manual for the JOVIAL (J73) Language, RADC-TR-81-143, Final Technical Report of June 1981.

    1.1.3 Calculations

    In the simplest case, calculations is performed by an assignment
    statement.  An example is:

    AVERAGE = (X1 + X2)/2;

    The right-hand-side of this assigment is a formula; it forms the
    sum of X1 and X2 and divides it by 2.  The details of the
    operation depend on how X1 and X2 are declared.  If X1 and X2 are
    declared float, the calculation is very likely to produce the
    expected result.  In contrast, if the X1 and X2 are declared
    fixed, the scaling must be worked out by the programmer to make
    sure the calculation will succeed.  And if X1 and X2 are declared
    character-string, the compiler will reject it because JOVIAL does
    not automatically convert values into the types required by
    operators.

    In the example just given, the parenthesis show that the addition
    is performed before the division.  When parenthesis are not
    given, JOVIAL recognizes the usual order of evaluation.  Here is
    an example:

         POLY = BETA*X1**2 - GAMMA*X2 + DELTA;

    JOVIAL applies its "rules of precedence" to the formula in this
    assignment and thus interprets it as:

         POLY = (((BETA*(X1**2)) - (GAMMA*X2)) + DELTA);

    The complete precedence rules are given in Chapter 11.

    Chapter 1 Introduction, page 6

    The examples just given illustrate the use of formulas on the
    right-hand side of an assignment statement.  A formula can also
    appear as part of the left-hand side of an assignment statement;
    for example, as the subscript of an array  In addition to their
    important role in assignment statements, formulas can appear in
    many other places in the language: as actual parameters of
    functions and prcedures, as the condition in an if-statement,
    and so on.

    Since JOVIAL has quite a few kinds of values, it must have many
    ways of converting one kind of value into another kind.  In most
    cases, you must explicitly indicate the conversion.  An example
    is:

         ITEM MARK U 10;
         ITEM TIME F;
         ...
         MARK = (* U 16 *) (TIME);

    The value of the floating item TIME is converted to a ten-bit
    integer value before it is assigned to the ten-bit integer item
    MARK.  If you leave the conversion operator out of this
    assignment, the compiler will report an error.  The compiler
    catches situations in which one type of value is uninetentionally
    assigned to or combined with a different type of variable.

    Chapter 1 Introduction, page 7

assembly language instructions

data movement

    Data movement instructions move data from one location to another. The source and destination locations are determined by the addressing modes, and can be registers or memory. Some processors have different instructions for loading registers and storing to memory, while other processors have a single instruction with flexible addressing modes. Data movement instructions generally have the greatest options for addressing modes. Data movement instructions typically come in a variety of sizes. Data movement instructions destroy the previous contents of the destination. Data movement instructions typically set and clear processor flags. When the destination is a register and the data is smaller than the full register size, the data might be placed only in the low order bits (leaving high order bits unchanged), or might be zero- or sign-extended to fill the entire register (some processors only use one choice, others permit the programmer to choose how this is handled). Register to register operations can usually have the same source and destination register.

    Earlier processors had different instructions and different names for different kinds of data movement, while most modern processors group data movement into a single symbolic name, with different kinds of data movement being indicated by address mode and size designation. A load instruction loads a register from memory. A store instruction stores the contents of a register into memory. A transfer instruction loads a register from another register. In processors that have separate names for different kinds of data moves, a memory to memory data move might be specially designated as a “move” instruction.

    An exchange instruction exchanges the contents of two registers, two memory locations, or a register and a memory location (although some processors only have register-register exchanges or other limitations).

    Some processors include versions of data movement instructions that can perform simple operations during the data move (such as compliment, negate, or absolute value).

    Some processors include instructions that can save (to memory) or restore (from memory) a block of registers at one time (useful for implementing subroutines).

    Some processors include instructions that can move a block of memory from one location to another at one time. If a processor includes string instructions, then there will usually be a string instruction that moves a string from one location in memory to another.

See also Data Movement Instructions in Assembly Language

    Professors are invited to give feedback on both the proposed contents and the propsed order of this text book. Send commentary to Milo, PO Box 1361, Tustin, California, 92781, USA.


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, 2012 Milo

    Created: October 31, 2010

    Last Updated: September 22, 2012


return to table of contents
free downloadable college text book

previous page next page
previous page next page