CMP EMBEDDED.COM

Login | Register     Welcome Guest ESC Boston  esc india  Call for Abstracts
 

Into, but not out of, the void
C and C++ both use void * as the generic data pointer type, but they treat it differently. Here's some insight into why.



Embedded.com

The early dialect of C described by Kernighan and Ritchie (Kernighan, Brian W. and Ritchie, Dennis M., The C Programming Language. Prentice Hall, 1978.) (often called "Classic C") didn't include the keyword void, and therefore had no type void *. Lacking void *, Classic C programs tended to use char * as the type for a "generic" data pointer--a pointer that can point to any data object. Unfortunately, this increased the need to use cast expressions.

For example, Classic C didn't include the now standard memory management functions malloc and free. On page 175 of their book, Kernighan and Ritchie implemented their own allocation function, alloc, which they defined as:

char *alloc(bytes)
unsigned bytes;
{
    ...
}

This function definition is in the old, non-prototyped style of Classic C. In Standard C, the equivalent declaration would be:

char *alloc(unsigned bytes);

This alloc function returns the address of the allocated storage as a pointer of type char *. However, they designed alloc to allocate storage for any type of object, not just char or array of char. When allocating storage for something other than a char (or array thereof), the program must convert the char * result into a pointer to the intended type of the allocated object--a conversion that requires a cast. Kernighan and Ritchie used casts to convert the result of calling alloc to something other than char *, in functions such as:

struct tnode *talloc()
{
   return ((struct tnode *)alloc(sizeof(struct tnode)));
}

1 | 2 | 3

Rate this article: Low High
Current rating
  • .
Embedded.com Career Center
Ready to take that job and shove it?
SEARCH JOBS

Browse all jobs

SPONSOR
RECENT JOB POSTINGS




 :