4 Variables, Assignment, and Expressions

As in algebra, we assign symbolic names to the numbers and other elements we want to manipulate. In algebra y = x^2 + 2x + 1 is a statement about the relationship between x and y. We could also invert it to get the two values of x that correspond to a particular value of y. In programming

y = x * x + 2 * x + 1

is an assignment statement giving the instruction to start with the value stored at location x, multiply it by itself, add the product of the original value and 2, add 1 to the total, and then store the result in the location referred to symbolically as y. The order in which things happens may depend on the language, although it will usually follow the expected order for addition, subtraction, multiplication and division. Use parentheses when necessary to make the order of operations unambiguous to both people and computers.

Kernighan and Ritchie wrote that “The moral is that writing code that depends on order of evaluation is a bad programming practice in any language. Naturally, it is necessary to know what things to avoid, but if you don’t know how they are done on various machines, you won’t be tempted to take advantage of a particular implementation.” The same goes for order of evaluation differences between languages: being explicit decreases the chances of errors and increases the readability of your code for humans.

Defining and Initializing Variables

Defining a variable can only happen once, giving the variable a unique name, and allocating some storage space to save the value(s) associated with the variable.

int i;  // defines the variable i, could be global or local to a function
i = 5;  // assigns 5 to variable i, can only happen inside a function

is C code that defines the variable i as having type int, assigns a block of memory (either 2 or 4 bytes) large enough to hold an integer, then puts the integer value 5 in that storage space in memory.  The same could be accomplished in the combined statement:

int i = 5;  // could be global or local to a function

Always initialize your variables to avoid unexpected results. In Python or MATLAB this is simple: variables are defined automatically when you assign something to them and the type is set according to what you assigned to them. Get in the habit of writing real numbers with decimal points every time, e.g. 42.0 as it will never be wrong and will sometimes be important.

Be careful with the scope of your variables. A variable defined outside of a function is global and is available everywhere in your program code. A variable defined inside a function is local, and is available only inside that function, vanishing when the function finishes execution. Memory for local variables is only allocated when a function starts executing and the variables are trashed when the function finishes. The memory allocation may be in a different location each time, leading to potentially strange results if you don’t initialize every time.

If a local variable has the same name as a global variable, that local variable will be used throughout the function and the global variable ignored. Avoid using the same variable names as both globals and locals to minimize confusion. Same name errors can be hard to find when debugging.

Pick Good Variable Names

Pick names that are meaningful and/or follow conventions, even if the conventions are obsolete:

  • i, j, k are almost always used as integer counters, a throwback to Fortran where all variable names starting with i, j, k, l, m were integers and all the rest were real numbers.
  • x, y, z are almost always real numbers or cartesian positions in space.
  • radiusOfCurvature is easy to read as separate words and composed entirely of alpha characters, legal in any programming language.

Capitalize in a consistent way, or you will make mistakes that are hard to find. RadiusOfCurvature, radiusOfCurvature, and radiusofcurvature are three different variable names. Using lowerUpperUpper capitalization is a widely adopted convention.

Avoid letters that will be easily confused with numerals, especially upper case O and lower case l, which can be hard to differentiate from numerals 0 and 1. The O in radiusOfCurvature is unlikely to be seen as a zero.

Python

i = 5

creates a variable named i and assigns it the integer value 5.  You don’t need to worry about the difference between integers and floating point numbers. Python will choose accordingly.

Variables declared outside a function will be global. If you want to use them inside a function, you should include a global statement at the beginning of the function to refer to them explicitly.

def f(b):
    global a
    a += 1
    y = z
    return y * x + b * a

This function seems to leave z unspecified. Because it is assigned a value inside the function, y is a new variable, local to the function, even if it was also defined globally. The global value of a will be incremented by 1 because it is explicitly declared to be global. y will be assigned the value of the global variable z, if it exists, or throw an error for an undefined variable z if it doesn’t.

C

You need to pick a type for your variables that matches what you expect to store in them. Numbers should probably be int, long int, or double unless you have a good reason to choose otherwise. unsigned or unsigned long are good for things like time that increase to the limit of resolution and then should wrap around back to zero. All variables must be declared as a particular type before they can be used.

unsigned long timeLast = 0;
double sumX = 0.0;
int i = 0, j, k;

are all valid definition statements for variables, although you should be cautious of leaving variables uninitialized like j and k. ANSI C has rules about the automatic initialization of variables to 0 in some cases and random garbage in others – don’t depend on them unless you have looked them up, understand them, and can be sure you will remember them.

Global variables are available inside all functions without declaring them in the function. If you declare a variable of the same name inside a function, it will be a local variable, pointing to a different memory location and with a different value. Be careful to avoid creating a new variable when you are responding to “‘x’ was not declared in this scope” compiler errors, or you will wind up with two different variables both called x.

Static variables are a special case. Using the static keyword in declaring a local variable results in a variable that will only be visible locally, however it will remain at the same location in memory and the value will remain the same between calls to the function. This can allow functions to have some past history, e.g. to remember the time the function was last called.

 

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Rick's Measurement for Mechatronics Notes Copyright © 2019 by Rick Sellens is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book