Jan
31
Some of the best practices given below.
1. Prefer inline function over macros, bcz macro willl bring unwanted errors.
eg: See the example of a macro to find maximum of two numbers
#define MAX(a,b) (a > b) ? a : b
suppose if we used the macro as follows
int x = 20, y = 19;
int z = MAX(x, ++y);
now what is the value of z ? is it 20 ? or is it 19 ? .
.. he he …it is 21 !
Let us see , how it is happened,
Compiler will compile the code after macro expansion .. after macro expansion , the code will be as follows
int x = 20, y = 19;
int z = (x > ++y) ? x: ++y;
y has been incremented twice .. !
What is the solution:-
Use inline function… it will not produce unwanted errors … and high fast like macros bcz there is no function calling burdens
OR
Avoid complex expression when using macros… ie we can call the MAX as follows
int x = 20, y = 19;
++y;
int z = MAX(x, y);
2. Use call by reference other than call by value for big user defined data types.
//suppose we are having a class MyClass of size 100 bytes;
void foo(MyClass m) {
//some code
}
——————Instead use as follows ———————————
void foo(const MyClass& m) {
//some code
}
Explanation:
In both case we can call the method as follows
MyClass mc;
foo(mc);
In the first case a value of MyClass object, mc is copied to another object m, of MyClass.
Here Object of the MyClass has been created twice ie total 200 bytes used ..
also it will bring extra processing to initialize a new object.
In the second case , MyClass object is created only once then the alias of mc is created as m
there is no burden of new object initialization and processing.
The ‘const’ is used for two reason…
a) To avoid the misunderstanding that it is an output argument.
b) To avoid the accidental changes to the outside object from the function.
Note:- In C there is no call by reference but we are simulating call by reference
by passing address to the function argument and modifying the content of the address
from the function
3. Avoid unwanted file inclusion and prefer forward declaration.
Suppose Foo is a class and its definition is in Foo.h.
We are using the class Foo in the File MyClass.h as follows.
//MyClass.h
#include “Foo.h”
class MyClass {
Foo * aFoo;
//Some methods
}
———— Instead use as follows ————–
//MyClass.h
class Foo; // forward declaration.
class MyClass {
Foo * aFoo;
//Some methods
}
Explanation: -
In the first case, when including Foo.h , the entire code will be pasted in MyClass.h, it will
increase the size of executable and will creep in some unwanted errors.
We are not instantiating, or using the functionality of Foo, so the compiler should not bother about the size
of the class Foo ..it wants to know only what is Foo, we have forward declared it as ‘Class’.
Also aFoo is a pointer, the size of any pointer is the size of an integer.
so the compiler can allocate the size of pointer and it will not produce any error message.
4. Use header guard to avoid multiple inclusion of a file.
Filed under : iPhone Games
