16.05.2015 Views

Working with the Unix OS

Working with the Unix OS

Working with the Unix OS

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

C Programming – Basics<br />

struct tnode *talloc(void)<br />

{<br />

return (struct tnode *)malloc(sizeof(struct tnode));<br />

}<br />

char *strdup(char *s) /* make a duplicate of s */<br />

{<br />

char *p;<br />

p = (char *)malloc(strlen(s)+1); /* +1 for ’\0’ */<br />

if (p != NULL)<br />

strcpy(p, s);<br />

return p;<br />

}<br />

Unions<br />

A variable that holds, at different times, objects of different types and sizes, i.e. different data in a single area of<br />

storage.<br />

union u_tag {<br />

int ival;<br />

float fval;<br />

char *sval;<br />

}u;<br />

if (utype == INT)<br />

printf("%d\n", u.ival);<br />

else if (utype == FLOAT)<br />

printf("%f\n", u.fval);<br />

else if (utype == STRING)<br />

printf("%s\n", u.sval);<br />

else<br />

printf(" bad type id in utype\n", utype);<br />

A union is a structure in which all members have an offset zero from <strong>the</strong> base. Can only initialise value first<br />

member.<br />

Bit fields<br />

When storage space is at a premium, it may be necessary to pack several objects into a single machine word.<br />

The usual way this done us to define a set of "masks" corresponding to <strong>the</strong> relevant positions, as in<br />

#define KEYWORD 01<br />

#define EXTERNAL 02<br />

#define STATIC 04<br />

or<br />

enum { KEYWORD = 01, EXTERNAL = 02; STATIC = 04 );<br />

flags |= EXTERNAL | STATIC; /* turns bits on */<br />

flags & = ~(EXTERNAL | STATIC); /* turns bits off */<br />

if((flags &(EXTERNAL | STATIC)) == 0) /* both true */<br />

As an alternative C offers <strong>the</strong> capability of directly defining and accessing fields <strong>with</strong>in a word.<br />

struct{ /* 3 one bit fields */<br />

unsigned int is_keyword : 1;<br />

unsigned int is_extern : 1;<br />

unsigned int is_static : 1;<br />

}flags;<br />

flags.is extern = flags.is static = 1, /* bits on */<br />

flags.is extern = flags.is static = 0; /* bits off */<br />

if (flags.is extern == 0 && flags.is static == 0)<br />

Table Lookup<br />

Table lookup code is typically found in <strong>the</strong> symbol table management routines of a macro processor or a compiler.<br />

36

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!