Example Calculator program in C - describing use of External Variables in C

By: Daniel Malcolm Emailed: 1603 times Printed: 2075 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

A C program consists of a set of external objects, which are either variables or functions. The adjective ``external'' is used in contrast to ``internal'', which describes the arguments and variables defined inside functions. External variables are defined outside of any function, and are thus potentially available to many functions. Functions themselves are always external, because C does not allow functions to be defined inside other functions. By default, external variables and functions have the property that all references to them by the same name, even from functions compiled separately, are references to the same thing. (The standard calls this property external linkage.) In this sense, external variables are analogous to Fortran COMMON blocks or variables in the outermost block in Pascal. We will see later how to define external variables and functions that are visible only within a single source file. Because external variables are globally accessible, they provide an alternative to function arguments and return values for communicating data between functions. Any function may access an external variable by referring to it by name, if the name has been declared somehow.

If a large number of variables must be shared among functions, external variables are more convenient and efficient than long argument lists. However, this reasoning should be applied with some caution, for it can have a bad effect on program structure, and lead to programs with too many data connections between functions.

External variables are also useful because of their greater scope and lifetime. Automatic variables are internal to a function; they come into existence when the function is entered, and disappear when it is left. External variables, on the other hand, are permanent, so they can retain values from one function invocation to the next. Thus if two functions must share some data, yet neither calls the other, it is often most convenient if the shared data is kept in external variables rather than being passed in and out via arguments.

Let us examine this issue with a larger example. The problem is to write a calculator program that provides the operators +, -, * and /. Because it is easier to implement, the calculator will use reverse Polish notation instead of infix. (Reverse Polish notation is used by some pocket calculators, and in languages like Forth and Postscript.)

In reverse Polish notation, each operator follows its operands; an infix expression like

   (1 - 2) * (4 + 5)
is entered as
   1 2 - 4 5 + *
Parentheses are not needed; the notation is unambiguous as long as we know how many operands each operator expects.

The implementation is simple. Each operand is pushed onto a stack; when an operator arrives, the proper number of operands (two for binary operators) is popped, the operator is applied to them, and the result is pushed back onto the stack. In the example above, for instance, 1 and 2 are pushed, then replaced by their difference, -1. Next, 4 and 5 are pushed and then replaced by their sum, 9. The product of -1 and 9, which is -9, replaces them on the stack. The value on the top of the stack is popped and printed when the end of the input line is encountered.

The structure of the program is thus a loop that performs the proper operation on each operator and operand as it appears:

   while (next operator or operand is not end-of-file indicator)
       if (number)
           push it
       else if (operator)
           pop operands
           do operation
           push result
       else if (newline)
           pop and print top of stack
The operation of pushing and popping a stack are trivial, but by the time error detection and recovery are added, they are long enough that it is better to put each in a separate function than to repeat the code throughout the whole program. And there should be a separate function for fetching the next input operator or operand.

The main design decision that has not yet been discussed is where the stack is, that is, which routines access it directly. On possibility is to keep it in main, and pass the stack and the current stack position to the routines that push and pop it. But main doesn't need to know about the variables that control the stack; it only does push and pop operations. So we have decided to store the stack and its associated information in external variables accessible to the push and pop functions but not to main.

Translating this outline into code is easy enough. If for now we think of the program as existing in one source file, it will look like this:


    function declarations for main

    main() { ... }

    external variables for push and pop

   void push( double f) { ... }
   double pop(void) { ... }

   int getop(char s[]) { ... }
    routines called by getop

Later we will discuss how this might be split into two or more source files.

The function main is a loop containing a big switch on the type of operator or operand; this is a more typical use of switch .

   #include <stdio.h>
   #include <stdlib.h>  /* for  atof() */

   #define MAXOP   100  /* max size of operand or operator */
   #define NUMBER  '0'  /* signal that a number was found */

   int getop(char []);
   void push(double);
   double pop(void);

   /* reverse Polish calculator */
       int type;
       double op2;
       char s[MAXOP];

       while ((type = getop(s)) != EOF) {
           switch (type) {
           case NUMBER:
           case '+':
               push(pop() + pop());
           case '*':
               push(pop() * pop());
           case '-':
               op2 = pop();
               push(pop() - op2);
           case '/':
               op2 = pop();
               if (op2 != 0.0)
                   push(pop() / op2);
                   printf("error: zero divisor\n");
           case '\n':
               printf("\t%.8g\n", pop());
               printf("error: unknown command %s\n", s);
       return 0;
Because + and * are commutative operators, the order in which the popped operands are combined is irrelevant, but for - and / the left and right operand must be distinguished. In
   push(pop() - pop());   /* WRONG */
the order in which the two calls of pop are evaluated is not defined. To guarantee the right order, it is necessary to pop the first value into a temporary variable as we did in main.
   #define MAXVAL  100  /* maximum depth of val stack */

   int sp = 0;          /* next free stack position */
   double val[MAXVAL];  /* value stack */

   /* push:  push f onto value stack */
   void push(double f)
       if (sp < MAXVAL)
           val[sp++] = f;
           printf("error: stack full, can't push %g\n", f);

   /* pop:  pop and return top value from stack */
   double pop(void)
       if (sp > 0)
           return val[--sp];
       else {
           printf("error: stack empty\n");
           return 0.0;
A variable is external if it is defined outside of any function. Thus the stack and stack index that must be shared by push and pop are defined outside these functions. But main itself does not refer to the stack or stack position - the representation can be hidden.

Let us now turn to the implementation of getop, the function that fetches the next operator or operand. The task is easy. Skip blanks and tabs. If the next character is not a digit or a hexadecimal point, return it. Otherwise, collect a string of digits (which might include a decimal point), and return NUMBER, the signal that a number has been collected.

   #include <ctype.h>

   int getch(void);
   void ungetch(int);

   /* getop:  get next character or numeric operand */
   int getop(char s[])
       int i, c;

       while ((s[0] = c = getch()) == ' ' || c == '\t')
       s[1] = '\0';
       if (!isdigit(c) && c != '.')
           return c;      /* not a number */
       i = 0;
       if (isdigit(c))    /* collect integer part */
           while (isdigit(s[++i] = c = getch()))
       if (c == '.')      /* collect fraction part */
           while (isdigit(s[++i] = c = getch()))
       s[i] = '\0';
       if (c != EOF)
       return NUMBER;

C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

what is the use of int getch(void)
and ungetch

View Tutorial          By: sania at 2014-06-04 17:15:30

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Daniel Malcolm
javac options in Java
Operator Precedence in Java
Calling Multiple Listeners in JSF
Using free() Function in C
ForwardAction in Struts
Listing Files and Directories sample program in C
Binary Tree - (Self-referential Structures) example program in C
A simple program using EL in JSP
Command-line Arguments in C
Example Calculator program in C - describing use of External Variables in C
Assignment Operators and Expressions in C
The for statement in C
JSF Basics
assert() Versus Exceptions in C++
RMS Basics in J2ME

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
Using memset(), memcpy(), and memmove() in C
Listing Files and Directories sample program in C
perror() Function - example program in C
Open, Creat, Close, Unlink system calls sample program in C
UNIX read and write system calls sample program in C
Using free() Function in C
assert() Function Example program in C
scanf and sscanf sample program in C
Sum of the elements of an array in C
Printing a simple histogram in C
lseek() sample program in C
fgets(), fputs() - Line Input and Output - sample program in C
Fopen and Getc implementation program in C
Sorting an integer array in C
Find square and square root for a given number in C
Most Emailed Articles (in C)
Address Arithmetic and pointers in C
Macro Substitution using #define in C
Pointers to Structures example program in C
Getting Started with C
Variables and Arithmetic Expressions in C
register Variables in C
Trigonometric, Hyperbolic, Exponential and Logarithmic Functions in C
Printing a simple histogram in C
Symbolic Constants using #define in C
Arguments - Call by Value in C
Conditional Expressions in C
Functions returning non-integer values in C
Recursion in C
Tutorial on Complicated Declarations in C
Standard Input and Output in C