15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The following code represents our library of C functions which we want to wrap so that we<br />

can use this code from within the <strong>Python</strong> interpreter. main() is our tester function.<br />

1 #include <br />

2 #include <br />

3 #include <br />

4<br />

5 int fac(int n)<br />

6 {<br />

7 if (n < 2) return(1); /* 0! == 1! == 1 */<br />

8 return (n)*fac(n-1); /* n! == n*(n-1)! */<br />

9 }<br />

10<br />

11 char *reverse(char *s)<br />

12 {<br />

13 register char t, /* tmp */<br />

14 *p = s, /* fwd */<br />

15 *q = (s + (strlen(s)-1)); /* bwd */<br />

16<br />

17 while (p < q) /* if p < q */<br />

18 { /*swap & mv ptrs */<br />

19 t = *p;<br />

20 *p++ = *q;<br />

21 *q-- = t;<br />

22 }<br />

23 return s;<br />

24 }<br />

25<br />

26 int main()<br />

27 {<br />

28 char s[BUFSIZ];<br />

29 printf("4! == %d\n", fac(4));<br />

30 printf("8! == %d\n", fac(8));<br />

31 printf("12! == %d\n", fac(12));<br />

32 strcpy(s, "abcdef");<br />

33 printf("reversing 'abcdef', we get '%s'\n", \<br />

34 reverse(s));<br />

35 strcpy(s, "madam");<br />

36 printf("reversing 'madam', we get '%s'\n", \<br />

37 reverse(s));<br />

38 return 0;<br />

39 }<br />

The last piece of code is the required main() function. We use it to be our tester, sending various<br />

arguments to fac() and reverse() . With this function, we can actual tell whether our code works (or<br />

not).<br />

Now we should compile the code. For many versions of Unix with the gcc compiler, we can use the<br />

following command:<br />

$ gcc Extest1.c -o Extest<br />

$

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

Saved successfully!

Ooh no, something went wrong!