Operator Precedence

In mathematics there are rules of precedence that we are all familiar with. For example we know that given the expression 5+6/2 we must divide 2 into 6 before adding 5 to it. In other words, division has a higher precedence than additon. In C and C++ these rules of mathematical precedence have been expanded to include all of the operators in the language. So, for example, the * operator used to dereference a pointer ("get the contents at an address"), has a higher precedence than addition.

C Code
  1: #include <stdio.h>
  2: 
  3: int main()
  4: {
  5:   short age[4]; 
  6:   age[0]=23;
  7:   age[1]=34;
  8:   age[2]=65;
  9:   age[3]=74;
 10: 
 11:   printf("%x\n", *age+1);
 12:   return 0;
 13: }
C++ Code
  1: #include <iostream>
  2: 
  3: int main()
  4: {
  5:   short age[4]; 
  6:   age[0]=23;
  7:   age[1]=34;
  8:   age[2]=65;
  9:   age[3]=74;
 10: 
 11:   std::cout << *age+1 << std::endl;
 12:   return 0;
 13: }
In this example, since the dereference operator has a higher precedence, first the contents of the address at age would be retrieved and then 1 would be added to it. Since age is the address of the first element of the array, *age returns 23, then 1 is added resulting in 24 printing out. This isn't what we want. What we want is for the value of the second element of the array to print out. In order to change the order that the operators are evaluated, we use the same technique used in mathematics--parentheses. That is why the expression needs to be *(age+1).