Department of Engineering

IT Services

C habits to give up

C++ is a flexible language. You can write C++ that a C compiler could compile. You can even write in a style that isn't too distant from Fortran 77. But if you're a C programmer who wants to make the most of modern C++, the following points are worth bearing in mind

  • Think in terms of objects rather than functions. Groups of objects are easier to organise (using inheritance) than are groups of functions.
  • Use namespaces: functions can have shorter names; information hiding is easier; and it's easier to switch between different implementations. Use namespace rather than files to control scoping.
  • Use references rather than pointers when you can.
  • Use strings. You can convert between C and C++ strings

      char cstring[]="a test"; 
      string a_str;
      a_str=string(cstring);
      strcpy(cstring, a_str.c_str());
    

  • Don't use NULL - use 0
  • Create variables just before first use. In particular, create for loop index variables within the loop construction.
  • Use exceptions when the code that has to deal with a problem is far from the code that discovers the problem.
  • Use const as much as possible. Note that in C++, const variables have internal linkage by default whereas in C, they have external linkage.
  • Use enum
  • Don't use type-identifer fields in structures
  • Avoid pre-processor macros. const, inline, template and namespace replace most of #define usage, leading to stronger typing and better control of scope. For example

    const int answer = 42;
    template<class T> inline T min(T a, T b) {return (a<b)?a:b;}
    

  • Avoid static except within functions.

    // better than a global
    int & use_count()
    {
    static int uc =0;
    return uc;
    }
    

    or use nameless namespaces

    namespace {
    class X{};
    void f(); // like a static
    int i;
    }