Tuesday, April 18, 2006

Preprocessor Operators

Stringizing Operator:
#define Strings(X) cout<<#x

calling:
Strings( hai );

Replaces as:
"Hai"

output:
Hai

Charizing Operator:
#define Chars(X) #@X
calling:
a = Chars( b );
Replaces as:
'b'

Token-Pasting Operator:
#define tokens(X) cout< a##x
calling:
int ab=10;
tokens( b );
Replaces as:
ab

Can a structure have a fn pointer?

Yes..lookout the following example,


/*
Question> Can a structure have a fn pointer?
*/

typedef struct tagEMP
{
int no1;
int no2;
int ( *FuncPtr )( int, int );
int result;

}stEMP;

static int Add( int a, int b );
static int Sub( int a, int b );

int main( void )
{
stEMP stEmps;

stEmps.no1 = 10;
stEmps.no2 = 5;

stEmps.FuncPtr = &Add;
stEmps.result = stEmps.FuncPtr( stEmps.no1, stEmps.no2 );
clrscr( );
printf( "Result is %d\n", stEmps.result );

return 0;
}

static int Add( int a, int b )
{
return ( a+ b );
}


static int Sub( int a, int b )
{
return ( a - b );
}

Thursday, April 06, 2006

Storage Classes

C has a concept of 'Storage classes' which are used to define the scope (visability) and life time of variables and/or functions.

auto - storage class
auto is the default storage class for local variables.
{
int Count;
auto int Month;
}
The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.

register - Storage Class
register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location).

{
register int Miles;
}

Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implimentation restrictions.

static - Storage Class
static is the default storage class for global variables. The two variables below (count and road) both have a static storage class.

'static' can also be defined within a function. If this is done, the variable is initalised at compilation time and retains its value between calls. Because it is initialsed at compilation time, the initalistation value must be a constant. This is serious stuff - tread with care.

extern - storage Class
extern defines a global variable that is visable to ALL object modules. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined.