2 !!DESCRIPTION!! OTCC Example (simple K&R Style)
4 !!LICENCE!! GPL (?), read COPYING.GPL
10 * Sample OTCC C example. You can uncomment the first line and install
11 * otcc in /usr/local/bin to make otcc scripts !
14 /* Any preprocessor directive except #define are ignored. We put this
15 include so that a standard C compiler can compile this code too. */
19 /* defines are handled, but macro arguments cannot be given. No
20 recursive defines are tolerated */
21 #define DEFAULT_BASE 10
23 #ifdef NO_IMPLICIT_FUNC_PROTOTYPES
28 * Only old style K&R prototypes are parsed. Only int arguments are
29 * allowed (implicit types).
31 * By benchmarking the execution time of this function (for example
32 * for fib(35)), you'll notice that OTCC is quite fast because it
33 * generates native i386 machine code.
37 printf("[fib(%d)]", n);
41 return fib(n-1) + fib(n-2);
44 /* Identifiers are parsed the same way as C: begins with letter or
45 '_', and then letters, '_' or digits */
48 /* local variables can be declared. Only 'int' type is supported */
52 /* 'while' and 'for' loops are supported */
58 /* Well, we could use printf, but it would be too easy */
59 print_num(long n,int b)
62 /* Numbers can be entered in decimal, hexadecimal ('0x' prefix) and
64 /* more complex programs use malloc */
69 /* Character constants can be used */
77 /* 'break' is supported */
83 printf("%c", *(char *)p);
88 /* 'main' takes standard 'argc' and 'argv' parameters */
89 mymain(int argc,char **argv)
91 /* no local name space is supported, but local variables ARE
92 supported. As long as you do not use a globally defined
93 variable name as local variable (which is a bad habbit), you
94 won't have any problem */
98 /* && and || operator have the same semantics as C (left to right
99 evaluation and early exit) */
100 if (argc != 2 && argc != 3) {
101 /* '*' operator is supported with explicit casting to 'int *',
102 'char *' or 'int (*)()' (function pointer). Of course, 'int'
103 are supposed to be used as pointers too. */
108 /* Any libc function can be used because OTCC uses dynamic linking */
112 base = atoi(argv[2]);
113 if (base < 2 || base > 36) {
114 /* external variables can be used too (here: 'stderr') */
115 fprintf(stdout, "Invalid base\n");
119 printf("fib(%d) =\n", n);
120 print_num(fib(n), base);
123 printf("fact(%d) = ", n);
127 /* why not using a function pointer ? */
129 print_num((*(long (*)(int))f)(n), base);
135 /* functions can be used before being defined */
138 printf("usage: %s n [base]\n", name);
139 printf("Compute fib(n) and fact(n) and output the result in base 'base'\n");
146 argv[1]="10"; /* n */
147 argv[2]="8"; /* base */