(M)  s i s t e m a   o p e r a c i o n a l   m a g n u x   l i n u x ~/ · documentação · suporte · sobre

  Next Previous Contents

10. Pointers are problems

Pointers are not required for general purpose programming. In modern languages like Java there is no support for pointers (Java internally uses pointers). Pointers make the programs messy and programs using pointers are very hard to read.

Avoid using pointers as much as possible and use references. Pointers are really a great pain. It is possible to write an application without using pointers. You should pointers only in those cases where references will not work.

A reference is an alias; when you create a reference, you initialize it with the name of another object, the target. From the moment on, the reference acts as an alternative name of the target, and anything you do to the reference is really done to the target.

Syntax of References: Declare a reference by writing the type, followed by the reference operator (&), followed by the reference name. References MUST be initialized at the time of creation. For example -


        int             weight;
        int     & rweight = weight;

        DOG             aa;
        DOG & rDogRef = aa;

Do's of references -

  • Do use references to create an alias to an object
  • Do initialize all references
  • Do use references for high efficiency and performance of program.
  • Do use const to protect references and pointers whenever possible.

Do not's of references -

  • IMPORTANT: Don't use references to NULL objects
  • Don't confuse the address of operator & with reference operator. The references are used in the declarations section (see Syntax of References above).
  • Don't try to reassign a reference
  • Don't use pointers if references will work
  • Don't return a reference to a local object
  • Don't pass by reference if the item referred to may go out of scope


Next Previous Contents