Using expressions in C++

A C++ program contains a number of expressions. For example when you write "x = ... ;" the "..." is an expression to be evaluated and inserted into x. Similarly in "if (expr) { ...}" the expr is an expression to be evaluated to true or false.

Expressions are built from operators like +, -, *, /, which typically combine one or two subexpressions. (The operators +, -, *, / are the usual arithmetic operators, and the star means multiply.)

Most operators, like +, * etc., operate on two subexpressions, on the left and right. The C++ compiler has to define the operator precidence, i.e. say which order an expression is evaluated in, such as whether addition or multiplication comes first in "x + y * z". It also as to define the operator associativity and say for exxample whether "x - y - z" means "(x - y) - z" (we say that - is "left associative") or "x - (y - z)" (this is what would have happened if - were "right associative", but it isn't). Fortunately we will see that C++ gets it right almost all of the time: * has higher precidence than + and - really is left associative.

There are examples of expressions throughout these web pages, and many expressions should come very naturally and easily. Some will need care.

In fact in "x = ... ;" the = is also an operator so the whole thing before the semicolon is an expression. The operator = has very low precidence which is why the righthand side is evaluated first.

Advice.

Operator precidence can always be overruled by using brackets (..). If in doubt, or if it increases readability, always use extra brackets.

Possible pitfalls.

Common errors include:

A table of operators.

We list a number of popular operators by precidence (highest precidence, i.e. most binding first) and state what they normally do, and their associativity where the associativity is not to the left. You will see that a number of operators have the same precidence, so in these cases the order of operators is determined by their associativity. This list is deliberately not complete. Quite a lot of it uses ideas we haven't covered here.

C++ has many more operators (this explains the missing levels!) but the ones above should be more than enough for normal programming in numerics. Amongst the ones I have missed out are operators relating to pointers and bitwise operators.