Notes - C/C++ Tricks

.plan
[Last 5] [Last 10] [Index] [RSS Feed] [Full .plan]
Contact Me
Todo Chart (aka: How busy is Dylan?)

Research

ZFS Timeline Forensics

Notes

Notes
Security
Vim
C and C++
FreeBSD
more notes...

Software

Codepile
Assorted little scripts and apps.
rastodo.py
Commandline/Android ToDo list stored in a text file.
Android Apps
more software...

Game Mods

LethalMod
A Max Payne 2 mod - more realistic and deadly.
more mods...

RMITCS

C Helpdesk Resources
Customising Your CS Account
more RMITCS stuff...

Roleplaying Games

Shadowrun Notes(4th ed)
Heavy Gear Notes(2nd ed)
more RPG stuff...

Portfolio

Portfolio
Examples of my University work.

Miscellaneous

links
Old Image Gallery
Taglines
crazy
Trombone slide position chart [PDF]
[Back to home page]
[Back to Index]

[Raw XML]
Assorted C/C++ tips and tricks.

Contents:

If you have any suggestions or corrections feel free to mail me. Note that the examples are illustrative and few have been actually tested.

Many of these topics are my own notes on obscure/advanced stuff I only use occasionally. I've indicated with (advanced) where there are some things that should not be attempted by novice programmers. A similar (non-portable) tag is used for some non-portable tricks.

Preventing Assignment/Equality Bugs

If compairing to a constant, the constant should be the lvalue (on the left).

This erroneous code will compile without errors (good compilers will warn you):

 
      while (foo = NULL)
         { ... }

The pointer foo will be set to NULL and the loop will never be entered. On the other hand, trying to build the following will always generate an error:

 
      while (NULL = foo)
         { ... }


   test.c: In function `main':
   test.c:7: error: invalid lvalue in assignment

Using Enumerations

Whenever you need to define a set of mutually exclusive states, always use an enumeration. Don't use an int and a bunch of #defines. If space is really a premium and you only need a few things, you could settle for a char 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).

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 #define.

 
//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 && bird1.velocity > 0.3)
   bs1 = FLYING;
 

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

 
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++
 

Using "Bitflags"

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 #defined for each bit position so you can easily manipulate it:

 
#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 & LOG_WARNINGS) == LOG_WARNINGS)
   ...

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

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

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

 

WARNING: 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 all others are unset. To test for a single flag you need to use & and == :

 
if (flags == LOG_WARNINGS) //DON'T DO THIS
   ...
if ((flags & LOG_WARNINGS) == LOG_WARNINGS) // The right way
   ...
if ((flags & (LOG_INCOMING | LOG_OUTGOING)) // Test for multiple flags set
         == (LOG_INCOMING | LOG_OUTGOING))
   ...
 

A variable that's really a function

Stolen from the FreeBSD errno manpage:


extern int * __error();
#define errno (* __error())

(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)

ANSI codes and colours

(non-portable)

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.

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.


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

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.

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


#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"

...

printf("%sI am blue!%s\n", ANSI_BLUE, ANSI_NORMAL);

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

Bit Masks

(advanced, non-portable)

Bit masks are where you specify the number of bits to use in a integral member of a class or struct. 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.

First rule of bit masks: Don't. 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.

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:


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 

You can use bit masks with a blank identifier to add some padding:


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 

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


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

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

Polymorphic Structures in C

(advanced)

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.

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

Example:


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;
}

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 physical position (first is best) in the struct/union. Alternatively, use a struct for the superclass and subclass:


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;
}


This requires extra typing "through" the union.

Generated Wed, 26 Nov 2014 23:43:42 +1100
Copyright © 2002-2014 Dylan Leigh.
[HTML 4.01 Transitional]