Site MapC++ Nugget Mine

If you have Cookies enabled,
you can check to see if any files you have downloaded
have been updated since you downloaded them
by clicking here.



A collection of succinct C++ code examples,
all free, beautiful and potentially gold-dust!

My intention is to provide simple, free access to usable solutions to common but difficult programming problems.

I have treated the creation of each class as a puzzle and hopefully have evolved good solutions.

If you know any better solutions then please e-mail me so that everyone can share your wisdom!

Be aware that I use a non-standard "Coding Style"... and its infectious...

A good place to start is the Site Map

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Coding Style

My coding style has developed as a result of years of programming in many languages.
Looking at my code will hurt your eyes for a day, but afterwards, you'll be reading my C++ in blocks instead of lines.
Your use of the scroll bars and printer may drop dramatically too!
A coding style should maximise your coding efficiency.
It should enable you to read and understand sections of code,
then blocks of code,
then lines of code,
then instructions.
and it should be used consistently.

Some languages (like LISP) require the programmer to efficiently manage parentheses and indents to great depths.
Heres a little routine written using my coding style:
CString GetNextWord() {
  char c;
  if(Msg.GetLength() > end-Msg) {
    stt=end;
    while(c=*stt++) {
      if(isLetter(c)) {
        end=stt;
        while(c);
          if(!isLetter(c=*end++)) {
            if(end-stt==1) break;
            return Msg.Mid(stt-Msg-1,end-stt);
  } } } } }
  return "";
}
(The above code has a deliberate bug, so don't use it!)
The first thing to notice is the "Lateral Thinking": a line of code does as much as possible which provides visual cues to the functionality of the block of code as a whole.
The code is also (vertically) a discrete lump which is easily identifiable when scrolling though the file.
If you have some awful bug - its not a complex enough example to be real, but say you have a compiler problem with:
          if(!isLetter(c=*end++)) {
you put it on separate lines while you debug:
          if(
          !isLetter(
          c=
          *end++
          )
          )
          {
The compiler will tell you which line the problem is: you correct the problem, then put the line back together so the code can be read as a block again.
Also laterally, I use the minimum number of delimiters to maintain readability of the block of code.
I could write
          if ( ! isLetter ( c = *end++ ) )
          {
          ...
          }
          else
          {
          }
but if there is no value in introducing spaces and delimiters and non-functional lines then don't!
If single line of Assembly Code is atomic (one instruction), then a single line of C++ should be molecular: the next level of discrete operation up.
I never do this:
  if(Condition)
    Operation();
Because its not clear: I see the if with a blank line under it and look for the closing brace but there isn't one.
so I always use the following patterns of "if" block:
  x=(Condition ? y : z);

  if(Condition) Operation(); else Operation();

  if(Condition) Operation();
  else          Operation();

  if(Condition) {
    Operation();
    Operation();
  }else{
    Operation();
    Operation();
  }

The last two examples are equivalent:

  if(Condition) {
    for(;;) {
      Operation();
      Operation();
    }
  }else{
    Operation();
    Operation();
  }

or:

  if(Condition) {
    for(;;) {
      Operation();
      Operation();
  } }
  else{
    Operation();
    Operation();
  }

Similarly vertical minimalism exists: I only insert blank lines where they mean something. I always use an indent of 2 spaces (the minimum that give a definite indent) and make tab characters turn into spaces. Tab characters slow your editing and at an indent of 2 they don't make much different to the source file size (which doesn't even matter any more).
Column Cut and Paste (hold down Alt and drag with the mouse) in Visual Studio means you have great coding speed advantages if you keep things in columns:
  output[j  ]=(unsigned char)( input[i]      & 0xFF);
  output[j+1]=(unsigned char)((input[i]>> 8) & 0xFF);
  output[j+2]=(unsigned char)((input[i]>>16) & 0xFF);
  output[j+3]=(unsigned char)((input[i]>>24) & 0xFF);
This principle needs restricting when declaring variables but is still useful in small blocks.

Most editors have a function to show you the matching bracket (), brace {} or parenthesis () - so I use it to make the code fit on one screen and put all the close braces together. Of course the braces still have to comply with the indentation for the vertical cue of a missing one... and this reverses their order... but don't panic! All you need to know is that you have the right number of braces!
Beginners may like to know that indenting consistently is one of the best way to avoid bugs.
I've seen people write:
          }
           //End If
        }
         //End while
      }
       //End If
    }
     //End while
  }
   //End If
  return "";
}
but that has no value; It actually makes you study the ends of the loops to see if theres any code amongst the comments. You may not get the whole function on-screen at once and have to print the code... "Time wasting"...
So I don't spend time writing verbosities, and that stops me spending time printing and reading them :-)
{he said, trying to hold the audience of verbosiphiles by reiterating}

The same principles apply to Comments.
I only use comments where the code isn't obvious or at least deducible.
The above code section would implement a Word-Finding algorithm (if it didn't have the deliberate bug)...
So if I see:
  if(...) {
    ...
    while(...) {
      if(...) {
        ...
        while(c);
          if(...) {
            if(...) break;
            return ...;
  } } } } }
  return "";
I'm likely to be looking at a Word-Finding section again. (Letting my brain do the pattern-matching thing that its best at).
Code is not meant to be a tutorial, so no comment should be necessary for the code - the function Name is self-explanatory.
If, however the function implemented a standard algorithm, like Binary Chop, the only comment necessary for this routine would be:
// Using Binary Chop Algorithm
If I'm releasing my code into the Wild Wild Web, The Binary Chop Algorithm would be a distinct class with a comment at the top of the header file describing the algorithm.

Multi-line comments don't need indents or starry borders, so I use:
/* Lots of comments here.
Kept to one sentence per line where possible because I have a high-resolution screen and a scroll bar and I know how to use them.
You may also be disgusted to know that I make Visual Studio display comments in this pink.
It allows my mind to flip between seeing code or comments... You probably have to try it!
Setting the background colour for strings to silver is also a great help in visually distinguishing code sections:
*/
CString S("OK" + ' ' + "heres coloured" + ' ' + "String Number " + itoa((x+2y-z*z)/4a) + " 4U.";
I also use the minimalist naming convention of capitalism: VeryLongName. I occasionally slip a p in for a pointer if its not obvious:
  char   Buffer[128];
  char* pBuffer=Buffer;
but I'd be more likely to give pBuffer a short obvious temporary name like ptr(pointer), src(source),dst(destination),it(iterator),S(string) unless it was an actual class member.

Most languages have conventions for the position of the declaration of variables and the naming of those variables,
but some scripting languages remove the need for any variable definitions.
I have never found a list of local variables useful, so I declare variables as close to their first usage as possible.
Obviously its important in C++ is that the Type of the variable is as useful as possible,
but do you trust a programmer who leaves left-over variable declarations for variables that are no longer used?
So if a variable in no longer used, that its definition should be easy to removed as well.
So you'll see things like:
  for(int i=0; i<5; ++i) {
Incidentally, I use ++i instead of i++ here because thats how you say it: "increment i" - and also because pre inc/dec compile to faster code than Post inc/dec because the latter need to store the old value before returning...
That doesn't really matter with modern PCs and C++; if you needed speed you'd use Assembly language, but knowing you're doing the best you can do gives satisfaction and thats the best reason for habitual optimisations!
Having said that, direct initialisation is probably faster (ie.
CString S("Hello")
rather than
CString S="Hello"
or
CMe::CMe() : x(0) {}
rather than
CMe::CMe() {x=0;}
but sometimes you can make code much more readable when you have many similarly used variables with:
 int a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4;
     a1=a2=a3=a4=b1=b2=b3=b4=c1=c2=c3=c4=d1=d2=d3=d4=0;

My last comment on coding regards formulae.
There are two types of formula: obvious and cryptic.
If its already cryptic, there is little point in making it pretty so I just make it safe.
I tend to write the shortest possible formula until I know that a formula may be messed up by a programmer.
When I need to make sure the compiler and I will always agree on a formula, everything in that formula suddenly gets smothered in parentheses (like in the days (before my time) when folk used Pre-processor Macros).
But it still goes on one line once its debugged!
Here are some examples:
  *dst++=Encode(((b2<<2) & 0x3C) | ((b3>>6) & 0x03));

  int    GetPin()       const {static const BYTE Pins[]={12,16,16,20,24,30,36,42,48,56,64,72,80,80}; return Pins[GetLoadGroup()==-1 ? 0 : GetLoadGroup()];}
  int    GetDevLength()       {return int(2*(GetTheta()*(0.5*GetClampID() + 2.5*GetFlatThick()) + 0.5*GetCBC() - (0.5*GetClampID() + 2.3*GetFlatThick()) * sin(GetTheta())) + 4*GetPin()+0.5);}
  double GetScantlingWeight() {return GetDevLength()*GetFlatWidth()*GetFlatThick()*Density;}
  double GetWeight()          {return 2*GetScantlingWeight()+GetPin()*(PI*GetPin()/3*GetGap()+4.5*GetPin()*GetPin())*Density;}
Since I may optimise formulae for the compiler I put the theory in Comments.

If anyone thinks its worth me maintaining or updating any of the above, please e-mail me.