Premature optimisation is the root of all evil.
1. I've often heard switch statements are preferred to if, else constructs. Does that make this second example better than the first one?
"often heard"? From whom? In what context? Use which ever is clearer for you situation.
if (x < 0){ // something}else{ // something else}
is clearer than
switch (x < 0){ case 0: // something break; default: // something else}
but
switch (x){ case 0: // something break; case 1: // something else break; case 2: // a third thing break; case 3: // yet another thing}
is probably clearer than
if (x < 2){ if (x == 0) { // something } else { // something else }}else{ if (x == 2) { // a third thing } else { // yet another thing }}
2. With all these special operators, do they make the program more efficient?
They are shorthand for the programmer, nothing more.
Quote:x++; x+=1; // same
In that instance, yes.
Quote:++x; x++; // any difference?
The first is preincrement - increment the value and use the new value, the second is postincrement - increment the value and use the old value. So:
int x = 0;func(++x); // calls func(1)assert(x == 1);func(x++); // calls func(1) againassert(x == 2);
Quote:x++; x+=20; // any difference?
The first increments x by one, the second increments x by 20.
Quote:x=x+20; x+=20; // same right?
Yes.
3. Are these special cases any different from the general cases?
Not all of the tests you posted do the same thing, so comparing speed makes no sense. Equivalent tests will be the same speed. One thing to note is this:
Quote:if (laserOn=1);
It is performing an assigment to laserOn and then using the value of laserOn as a boolean. Any good compiler will issue a warning for this.
4. Understanding pointer arithmetic.
Quote:((int*)(((short int*)(((char*)pointer)++))++))++;
Is not valid. You cannot repeatedly apply the postincrement operator since it returns the old value, which is a temporary. I'm sure someone will explain this a lot better, probably before I've gotten around to hitting the reply button :P
Quote:++((int*)(++( (short int*)(++((char*)pointer)) )) );
I'm not even going to attempt this one. Why on Earth would you want to do something like this?
5. Small and simple.
Quote:float f = 8.40f;
int i = 2;
// either of these faster?
result = ((int)f)/i;
result = (int)(f/i);
In this case the first would probably be fractionally faster, but not worth worrying about until after you've profiled your code and identified it as a bottleneck.
6. If I want to test if two small structs are equal without testing each member...
You're using C++. Write operator==(). Make it work
then make it fast.
Enigma