Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming Curing bracketitus
Back to top
On this page
Contents

Curing bracketitus

Experience shows that some students have a habit of putting brackets everywhere, even when they are not needed:

a = (b) + (c*d);       // Don't do this
x = (y) + (2 * (y*z)); // or this

presumably because they aren't quite sure whether they need brackets or not.

This is a bad idea because:

  1. The extra brackets are confusing
  2. It makes the markers think you do not understand either C or basic arithmetic

Mathematical precedence

The "mathematical" operators * / % + - have exactly the same effect as in ordinary maths, with % being treated on the same basis as * and /, that is to say:

  1. * / % bind more closely that + and -:
     
    2 * 3 + 1 => 7 not 4
    2 + 5 % 3 => 4 not 1
    
  2. Operators with the same precedence are evaluated from left to right:
     
    12 / 3 * 2   => 8 not 2
    

No implicit multiplication

In maths we often use implicit multiplication with single-character variable names:

s = ut + 0.5at2

expands to:

s = u*t + 0.5*a*t*t

Once we understand the implicit multiplication convention we see that C's treatment of */+- is exactly the same as we have been used to.

Now try the quiz.

Log in
                                                                                                                                                                                                                                                                       

Validate   Link-check © Copyright & disclaimer Privacy & cookies Share
Back to top