Archive

Archive for March, 2009

Speed Function Prototypes vs Switch vs if/else if statements

March 19th, 2009

When implimenting a state machine in c++ code it could be implimented using a Function Prototypes, Case /Switch statements, or If / Else if structures.  What is faster though?

I ran a couple of tests on Visual studio 2005.

book1_10149_image001

Function Prototypes are always slower than case statements.

If statements are only fastest when less than6 states are used.

Here is the quick and dirty code for testing.

Speed test code file

Sam Uncategorized

Static class members

March 18th, 2009

#include “stdafx.h”
#include <iostream>
#include <iomanip>
using namespace std;

class test{
public:
void hi(){
static int i=0;
cout << i++<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
test A;
test B;

A.hi(); //prints 0
A.hi();// prints 1
B.hi();// prints 2
int x;
cin >>x;
return 0;
}

Sam Uncategorized

Function Prototypes Example

March 18th, 2009

#include <iostream>
#include <iomanip>
using namespace std;

void Add(int x,int y);
void Sub(int x,int y);
void (* fun)(int x,int y);
int _tmain(int argc, _TCHAR* argv[])
{
int x;
cout <<”Test\n”;

fun = Add;
fun(1,2);
fun = Sub;
fun(1,2);
cin >> x;
return 0;
}
void Add(int x,int y){
cout << x+y<<endl;
}
void Sub(int x,int y){
cout << x-y<<endl;
}

Sam Uncategorized