<chunkynotes version="1.0" title="C/C++ Tricks">
   <summary>Assorted C/C++ tips and tricks.</summary>

<intro>
If you have any suggestions or corrections feel free to mail me. Note
that the examples are illustrative and few have been actually tested.<br/><br/>
Some of these topics are intended for intermediate to advanced C/C++
programmers and some are Considered Harmful(tm) by many coders. I've
indicated with <i>(advanced)</i> where there are some things that should not be
attempted by novice programmers. A similar <i>(non-portable)</i> tag is
used for some non-portable tricks.
</intro>

<!-- const, typedefs, etc -->

<!-- <chunk title="restrict, extern and volatile"> </chunk> -->

<chunk title="Using Enumerations">

<p>Whenever you need to define a set of <b>mutually exclusive
   states</b>, always use an enumeration. <b>Don't use an int and a
   bunch of <code>#define</code>s.</b> If space is really a premium and you only
   need a few things, you could settle for a <code>char</code> and a
   few letters as a code. If you need to represent some states that
   aren't mutually exclusive, use bitflags (see the next section).</p>
   
<p>An enumeration is basically an integer type associated with a bunch
   of special tokens. These tokens can be used for assignment and
   is-equal or not-equal checks - you can think of them as a sort of
   special <code>#define</code>.</p>

<sample> <src>
//declare the enumeration _type_
enum BirdState = {FLYING, LANDING, STANDING, TAKEOFF, EATING, SLEEPING};

//create a variable of it (in c or c++)
enum BirdState bs1 = SLEEPING;
//create a variable of it (in c++ only)
BirdState bs2 = SLEEPING;

//compare state
if (bs1 == EATING)
   bird1.hungry--;

//set and compare state
if (bs1 == TAKEOFF &amp;&amp; bird1.velocity > 0.3)
   bs1 = FLYING;
</src> </sample>

<p>There are some differences between <code>enum</code>s in C and C++.
   First, in C++ you do not need the <code>enum</code> keyword when
   declaring a variable. Second, in C++ you cannot use general integer
   operators (such as arithmetic and bitwise operators) on
   enumerations</p>

<sample> <src>
enum BirdState bs2;  // legal in C and C++
BirdState bs3;       // legal in C++ only

typedef enum BirdState BirdState_t
BirdState_t bs4;     // can use typedef like this
                     // to make it legal in C as well

bs2++;               // Illegal in C++
bs3 = 2;             // Illegal in C++
bs4 = bs2 | bs3;     // Illegal in C++
</src> </sample>

</chunk>

<chunk title="Using &quot;Bitflags&quot;">

<p>Bitflags are a method of storing multiple values, which are not
   mutucally exclusive, in one variable. You've probably seen them
   before. Each flag is a bit position which can be set on or off. You
   then have a bunch of bitmasks <code>#define</code>d for each bit
   position so you can easily manipulate it:</p>

<sample> <src>
#define LOG_ERRORS            1  // 2^0, bit 0
#define LOG_WARNINGS          2  // 2^1, bit 1
#define LOG_NOTICES           4  // 2^2, bit 2
#define LOG_INCOMING          8  // 2^3, bit 3
#define LOG_OUTGOING         16  // 2^4, bit 4
#define LOG_LOOPBACK         32  // and so on...

// Only 6 flags/bits used, so a char is fine
unsigned char flags;

// initialising the flags
// note that assignming a value will clobber any other flags, so you
// should generally only use the = operator when initialising vars.
flags = LOG_ERRORS;
// sets to 1 i.e. bit 0

//initialising to multiple values with OR (|)
flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING;
// sets to 1 + 2 + 8 i.e. bits 0, 1 and 3

// setting one flag on, leaving the rest untouched
// OR bitmask with the current value
flags |= LOG_INCOMING;

// testing for a flag
// AND with the bitmask before testing with ==
if (flags &amp; LOG_WARNINGS == LOG_WARNINGS)
   ...

// testing for multiple flags
// as above, OR the bitmasks
if (flags &amp; (LOG_INCOMING | LOG_OUTGOING)
         == (LOG_INCOMING | LOG_OUTGOING))
   ...

// removing a flag, leaving the rest untouched
// AND with the inverse (NOT) of the bitmask
flags &amp;= ~LOG_OUTGOING;

// toggling a flag, leaving the rest untouched
flags ^= LOG_LOOPBACK;

</src> </sample>

<p><b>WARNING:</b> DO NOT use the equality operator (i.e. bitflags ==
   bitmask) for testing if a flag is set - that expression will only
   be true if that flag is set and al others are unset. To test for a
single flag</p>

<sample> <src>
if (flags == LOG_WARNINGS) //DON'T DO THIS
   ...
</src> </sample>

</chunk>


<chunk title="A variable that's really a function">

<p>Stolen from the FreeBSD errno manpage:</p>

<sample><src>
extern int * __error();
#define errno (* __error())
</src>
</sample>

<p>(Background: This allows __error() to return a errno for a specific thread
instead of using a single global errno that could be wiped out by
another thread)</p>

</chunk>

<chunk title="ANSI codes and colours">
<blockquote><i>(non-portable)</i></blockquote>

<p>First of all, make sure you're checking terminal types or at least
providing a monochrome option so people who use terms that don't
support this don't suffer excape characters all over their text.</p>

<p>The codes themselves have a starting sequence, (Escape-[ or \033[)
then a set of numbers seperated by semicolons which may contain a text
attribute normal, bold, underlined, blinking...) and foreground and
background colours. The code is closed with an m.</p>

<pre><small>
Properties   Properties       Foreground     Background
             (disable)
0 normal                      30 black       40 black
1 bold       22 unbold        31 red         41 red
4 underline  24 ununderline   32 green       42 green
5 blink      25 unblink       33 yellow      43 yellow
7 inverse    27 uninverse     34 blue        44 blue
9 strike     29 unstrike      35 magenta     45 magent
                              36 cyan        46 cyan
                              37 white       47 white
                              39 default     49 default

</small></pre>

<p>Attributes are not as widely supported as simple colours. Often in
an X environment the user has chosen a bold font and bold will have no
effect; underlined, blinking and inverse text sometimes fail for no
particular reason. The codes for cancelling an attribute (unbold etc)
sometimes do something completely different. Strikethrough is
"standard" but I've never seen it actually work.</p>

<p>For these reasons you're probably better off just sticking with the
colours. A C example follows:</p>

<sample>
<src>
#define ANSI_NORMAL  "\033[0m"

/* these are all normal text with black background (40) */
#define ANSI_RED     "\033[0;31;40m"
#define ANSI_GREEN   "\033[0;32;40m"
#define ANSI_YELLOW  "\033[0;33;40m"
#define ANSI_BLUE    "\033[0;34;40m"
#define ANSI_MAGENTA "\033[0;35;40m"
#define ANSI_CYAN    "\033[0;36;40m"
#define ANSI_WHITE   "\033[0;37;40m"

#define ANSI_BOLD_RED      "\033[1;31;40m"
#define ANSI_UNDERLINE_RED "\033[4;31;40m"
#define ANSI_BLINK_RED     "\033[5;31;40m"
</src>
...
<src>
printf("%sI am blue!%s\n", ANSI_BLUE, ANSI_NORMAL);
</src>
</sample>

<p>Always, <b>always</b> close the text with the \033[0m code (normal
text) or else the text after your program ends will be affected...</p>

</chunk>

<chunk title="Bit Masks">
<blockquote><i>(advanced, non-portable)</i></blockquote>
<p>Bit masks are where you specify the number of bits to use in a <b>integral
member</b> of a <b>class or struct</b>. C has more restrictions than C++ on
this. In particular, only "int", "signed int" or "unsigned int" can have bit
masks in C. Many C compilers ignore bit masks altogether.</p>

<p>First rule of bit masks: <b>Don't</b>. Don't unless you have a really bad
need to save a tiny amount of memory, and slowing down your code a lot isn't a
problem (the compiler will have to work around things as they are not properly
aligned). Bit masks are also inherently non-portable and differ on different
compilers on different machines. Some compilers will ignore them totally.</p>

<p>If you really want to go ahead with it, all you do is put a colon after the
member followed by the number of bits it should occupy. Here's an example:</p>

<sample>
<src>
struct TwelveHourTime
{
   unsigned hour     : 4;     //4 bits (16), enough for 1-12
   unsigned minute   : 6;     //6 bits (64), enough for 0-59
   unsigned am       : 1;     //1 bit, on for am off for pm
};

//   0 1 2 3 4 5 6 7 8 9 A
//  |_ _ _ _|_ _ _ _ _ _|_|
//    hour     minute    am 
</src>
</sample>

<p>You can use bit masks with a blank identifier to add some padding:</p>

<sample>
<src>
struct TwelveHourTime
{
   unsigned hour     : 4;     //4 bits (16), enough for 1-12
   unsigned minute   : 6;     //6 bits (64), enough for 0-59
   unsigned          : 5;     //5 unused bits
   unsigned am       : 1;     //1 bit, on for am off for pm
};

//   0 1 2 3 4 5 6 7 8 9 A B C D E F
//  |_ _ _ _|_ _ _ _ _ _|_ _ _ _ _|_|
//    hour     minute    (unused)  am 
</src>
</sample>

<p>You can a blank identifier with bit mask of 0 to force the next element to
align to the boundary of the given type:</p>

<sample>
<src>
struct TwelveHourTime
{
   unsigned hour     : 4;     //4 bits (16), enough for 1-12
   char              : 0;     //push minute to the next byte boundary
   unsigned minute   : 6;     //6 bits (64), enough for 0-59
   unsigned am       : 1;     //1 bit, on for am off for pm
};

//   0 1 2 3 4 5 6 7 8 9 A B C D E
//  |_ _ _ _|_ _ _ _|_ _ _ _ _ _|_|
//    hour  (unused)  minute     am
</src>
</sample>

<p>Again, bit masks are very non-portable and the exact layout depends on the
compiler and platform. The diagrams are a guide only.</p>

</chunk>

<chunk title="Polymorphic Structures in C">
<blockquote><i>(advanced)</i></blockquote>
<p>This can be achieved with a little creative union and struct work. The
basic idea is to have a structure representing a superclass, which contains a
union of all the other subclasses.</p>

<p>You will need another entity (preferably an enumeration) in the superclass
and all subclasses to determine what type of struct it is.</p>

<p>Example:</p>
<sample>
<src>
typedef struct{
   int type;
   float ypos;
   float xpos;
   float length;
   float height;
} Shape_Triangle

typedef struct{
   int type;
   float ypos;
   float xpos;
   float length;
} Shape_Square

typedef struct{
   int type;
   float ypos;
   float xpos;
   float radius;
} Shape_Circle

typedef union{
  int type;
  Shape_Square square;
  Shape_Triangle triangle;
  Shape_Circle circle;
} Shape;

...

Shape s = getShape();
switch(s.type)
{
   case SHAPE_SQUARE:
      s.Shape_Square.length=3;
      break;
   case SHAPE_TRIANGLE:
      s.Shape_Triangle.height=4;
      break;
   case SHAPE_CIRCLE:
      s.Shape_Circle.radius=5;
      break;
}
</src>
</sample>

<p>A drawback of this method is that you need to duplicate the members in the
substructure, and you must make sure the type variables are all in the
same <b>physical</b> position (first is best) in the struct/union. Alternatively, use a struct for the superclass and subclass:</p>

<sample>
<src>
typedef struct{
   float length;
   float height;
} Shape_Triangle

typedef struct{
   float length;
} Shape_Square

typedef struct{
   float radius;
} Shape_Circle

typedef union{
  Shape_Square square;
  Shape_Triangle triangle;
  Shape_Circle circle;
} Shape_Union;

typedef struct{
   int type;
   float xpos;
   float ypos;
   Shape_Union subshape;
}

...

Shape s = getShape();
switch(s.type)
{
   case SHAPE_SQUARE:
      s.subshape.Shape_Square.length=3;
      break;
   case SHAPE_TRIANGLE:
      s.subshape.Shape_Triangle.height=4;
      break;
   case SHAPE_CIRCLE:
      s.subshape.Shape_Circle.radius=5;
      break;
}

</src>
</sample>
<p>This requires extra typing "through" the union.</p>
</chunk>

</chunkynotes>
