An Introduction to Programming Languages: Simultaneous Learning in Multiple Coding Environments by Paul A. Gagniuc

An Introduction to Programming Languages: Simultaneous Learning in Multiple Coding Environments by Paul A. Gagniuc

Author:Paul A. Gagniuc
Language: eng
Format: epub
ISBN: 9783031232770
Publisher: Springer International Publishing


4.4.3 Multiple Assignments

What kind of optimization can be implemented for multiple variables that store the same value? The answer to this question is given by multiple assignments. Usually, variables are declared one by one in a separate manner, namely, on separate lines. Computer languages such as Visual Basic 6.0, Python or JavaScript allow the assignment of a single value to several variables simultaneously. For instance, let us consider three variables, namely a, b and c. In normal cases, by using the simple assignment method, the following statements are true, namely: “a = 1; b = 1; c = 1;”. Note that the semicolon indicates the end of the statement just like in JavaScript, C++, C#, Java and so on. However, by using the multiple assignment method, those three different statements can be reduced to one, such as: “a = b = c = 1;”. Thus, all three variables have the same value, namely 1. By extension, value 1 can be replaced with a variable. Let us consider variable d, namely: “a = b = c = d;”, were variables a, b and c will take the value stored in variable d, whatever that value may be. This reduction is not only a cosmetic optimization, but an optimization that is also reflected at the hardware level in most computer languages. That is, because all three variables (a, b and c) are assigned to the same memory location. This multiple assignment optimization works the same whether a real primitive data type for an integer is involved (ex. VB) or an object that simulates a primitive data type for an integer is involved (ex. Ruby). The multiple assignment optimization as discussed above, is actually an old method. What is new instead, is the assignment of multiple objects to multiple variables. In Python for instance, one can assign multiple objects to multiple variables, namely a one-to-one correspondence like: (a, b, c = 3, “Paul”, 1). Thus, an integer with the value “3” is assigned to the variables a. A string with the value “Paul” is assigned to the variables b. An integer with the value “1” is assigned to the variables c. This optimization, however, is really more for syntax cosmetics and shortening the source code, which is otherwise very important.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.