Short-hand operators
 

  • C has many short-hand operators

  • Short-hand operators shortens an expression written using "non-short-hand" operators

    Example:

        Expression   Expression with a short-hand operator
        ==========   ========================================
        i = i + 1;   i++;    (combines = and + into 1 operator) 
        i = i * 7;   i *= 7; (combines = and * into 1 operator)
      


  • In fact:

    • Program languages created by European Computer Scientists (e.g.: Algol, Pascal, Modula) do not use any short-hand operators....

The pointer-member-access operator ->

Previous, we have used  (*p).fieldName  with reference variables to access member variables in a struct:

 #include <stdio.h>     

 struct BankAccount 
 {   
   int   ID;            
   float balance;
 };

 int main( int argc, char *argv[] )
 {
   struct BankAccount john, mary, *p ;

   john.balance = 500;
   p = &john;                    // Now *p ≡ john
   (*p).balance = (*p).balance + 2000; 

   mary.balance = 500;
   p = &mary;                    // Now *p ≡ mary
   (*p).balance = (*p).balance + 9000; 

   printf("j: %f  m:%f\n\n", john.balance, mary.balance); 
 }    

The pointer-member-access operator ->

The (binary) operator  ->  is a short hand operator for this combination of operations:  (* ). 

 #include <stdio.h>  // Operator -> is defined as:   p->x ≡ (*p).x 

 struct BankAccount 
 {   
   int   ID;            
   float balance;
 };

 int main( int argc, char *argv[] )
 {
   struct BankAccount john, mary, *p ;

   john.balance = 500;
   p = &john;                    // Now *p ≡ john
   (*p).balance = (*p).balance + 2000; 

   mary.balance = 500;
   p = &mary;                    // Now *p ≡ mary
   (*p).balance = (*p).balance + 9000; 

   printf("j: %f  m:%f\n\n", john.balance, mary.balance); 
 }    

The pointer-member-access operator ->

We can re-write this program using the  ->  operator as follows:

 #include <stdio.h>    // Program re-written using ->  

 struct BankAccount 
 {   
   int   ID;            
   float balance;
 };

 int main( int argc, char *argv[] )
 {
   struct BankAccount john, mary, *p ;

   john.balance = 500;
   p = &john;                    // Now *p ≡ john
   p->balance   = p->balance + 2000; 

   mary.balance = 500;
   p = &mary;                    // Now *p ≡ mary
   p->balance   = p->balance + 9000; 

   printf("j: %f  m:%f\n\n", john.balance, mary.balance); 
 }   

Notice the graphical similarity

  • The operator  ->  kinda depicts the fact that a reference variable points to another variable:

    In the above figure:

      • p points to the BankAccount struct variable (see the curved red arrow)

      • We can write p->balance to access the member variable balance

        The notation p -> balance depicts the fact that we are accessing another variable through the variable p