Thursday, August 03, 2006

Storage class, Type qualifier in C

Storage class:

auto --- default for local variables, can only be use within functions

register --- store in register instead of ram. Cannot apply '&' to it coz it has no memeory location. Usually used for small and often accessed variables. Not guarantee it is in register.

static --- default for global variables. If used within function, the variable is initialized as compile time and retains its value between calls

Because it is initialized at compile time, the initialization value must be constant.

char *mytest(char src[])
{
char tmp[10];
strcpy(tmp, src);
return tmp;
}

The pointer to the local array and is invalid as soon as function return

char *mytest(char src[])
{
static char tmp[10];
strcpy(tmp, src);
return tmp;
}

The storage assigned to 'tmp' will remain reserved for the duration.

Use pointer is better:
char *mytest(char src[])
{
char * tmp = new char[strlen(src) + 1];
strcpy(tmp, src);
return tmp;
}
char *y = mytest("abcdef");
delete [] y;

extern -- defines a global variable that is visable to all object modules. The variable cannot be initialized (variable is somewhere else)

Type qualifier

const ---

volatile ---compiler will not optimized this one. Used for memory-mapped hardware and involves shared memory.Each time the value is to be read, the value should be read directly from memory/register.

No comments:

Post a Comment