Precedence and Associativity of Operators

In C, when we have an expression with more than one operator in it, the rules that determine what order the operations are applied are called the precedence and associativity of the operators:

For operatores of different precedence, higher precedence are performed first. For operators of the same precedence, the associativity determines the order - left to right, or right to left.

So, for example, what order would the following epxression be evaluated in?

     x = -a + b * c + d / f / g

Applying these rules, our portfolio_value statement would be:

      portfolio_value =  shares * sell_whole  + sell_numer / sell_denomin;

evaluated as:

      portfolio_value = (shares * sell_whole) + (sell_numer / sell_denomin);

but we want:

      portfolio_value =  shares * (sell_whole +  sell_numer / sell_denomin);

We can put the prenetheses in our code to enforce that evaluation. When re compile and run the program, however, we still get the wrong answer. We need more debugging.

Manual tracing is always a good technique to help debug a program. It can at least help us "localize" where in the code the problem might be occurring. Unfortunatley, when we manually trace a program, we often "do what I meant" when we execute statements, which may not always be exactly what the C code says.

So, the next technique to apply, if tracing doesn't find the problem, is to let the computer do the tracing for us using debug lines.


[up] to Overview.