Hi,
I'm having a problem with one of the sample programs in the K&R book (second edition). Its the calculator program in chapter 4.
A good portion of questions in that chapter revolve around this program (whose source code they have provided). So i've tried compiling it, and it won't compile!
The problem appears to be that the symbolic constant "NUMBER" in polishCalc.c isn't being recognized in getop.c . Its declared outside all functions in polishCalc.c, so I don't understand why it isn't being recognized in getop.c. Interestingly enough, global variables seem to be recognized between the two source files... it is only with global symbolic constants that I'm having this problem.
It fails to work with and without "extern" before NUMBER.
Since the use of the constant is so trivial, it would take about .02 seconds to get the program to compile and work correctly. But why it isn't working is bothering me so much that I had to seek help.
Here's the code for the 2 aforementioned source files:
Code:
/*THIS IS polishCalc.c*/
#include <stdlib.h>
#include <stdio.h>
#define MAXOP 100
#define NUMBER 0
int getop(char s[]);
void push(double d);
double pop();
void polishCalc()
{
int type;
double op2;
char s[MAXOP];
while( (type = getop(s)) != EOF )
{
switch(type)
{
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if(op2 == 0)
printf("Error: Divisor is 0");
else
push(pop() / op2);
break;
case '\n':
printf("\t%.8g\n", pop());
break;
default:
printf("Error: Unknown command %s\n", s);
break;
}
}
}
Code:
/*THIS IS getop.c*/
#include <stdio.h>
#include <ctype.h>
int getch(void);
void ungetch(int);
int getop(char s[])
{
extern int NUMBER;
int i, c;
while( (s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
if(!isdigit(c) && c != '.')
return c;
i = 0;
if(isdigit(c))
{
while(isdigit( s[++i] = c = getch() ))
;
}
if(c == '.')
{
while(isdigit( s[++i] = c = getch() ));
;
}
s[i] = '\0';
if(c != EOF)
ungetch(c);
return NUMBER;
}
Can anyone help me out? Here are the 2 other referenced source files needed to completely compile the program if you need to:
Code:
/*THIS IS popPush.c*/
#include <stdio.h>
#define MAXVAL 100
int sp = 0;
double val[MAXVAL];
void push(double f)
{
if(sp < MAXVAL)
val[sp++] = f;
else
printf("Empty: stack full, can't push %g\n", f);
}
int pop(double f)
{
if(sp < 0)
return val[--sp];
else
{
printf("Error: Stack empty\n");
return 0.0;
}
}
Code:
/*THIS IS getUnget.c*/
#include <stdio.h>
#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++];
}