07.12.2012 Views

Object-Oriented Programming With ANSI-C (pdf)

Object-Oriented Programming With ANSI-C (pdf)

Object-Oriented Programming With ANSI-C (pdf)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

24 __________________________________________________________________________<br />

3 <strong>Programming</strong> Savvy — Arithmetic Expressions<br />

struct Node {<br />

enum tokens token;<br />

struct Node * left, * right;<br />

};<br />

This is not very flexible, however. We need to introduce a union to create a node<br />

in which we can store a numerical value and we waste space in nodes representing<br />

unary operators. Additionally, process() and delete() will contain switch statements<br />

which grow with every new token which we invent.<br />

3.5 Information Hiding<br />

Applying what we have learned thus far, we do not reveal the structure of a node at<br />

all. Instead, we place some declarations in a header file value.h:<br />

const void * Add;<br />

...<br />

void * new (const void * type, ...);<br />

void process (const void * tree);<br />

void delete (void * tree);<br />

Now we can code sum() as follows:<br />

#include "value.h"<br />

static void * sum (void)<br />

{ void * result = product();<br />

const void * type;<br />

for (;;)<br />

{ switch (token) {<br />

case ’+’:<br />

type = Add;<br />

break;<br />

case ’—’:<br />

type = Sub;<br />

break;<br />

default:<br />

return result;<br />

}<br />

scan(0);<br />

result = new(type, result, product());<br />

}<br />

}<br />

product() has the same architecture as sum() and calls on a function factor() to<br />

recognize numbers, signs, and a sum enclosed in parentheses:<br />

static void * sum (void);<br />

static void * factor (void)<br />

{ void * result;<br />

switch (token) {<br />

case ’+’:<br />

scan(0);<br />

return factor();

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

Saved successfully!

Ooh no, something went wrong!