Lecture #4
Programming Languages  MISHRA 95
 MISHRA 95
C Programming Language
UNIX operating system on the DEC
PDP-11.
BCPL,  Martin Richards. Late 60's.
   B,  Ken Thompson. 1970, First UNIX
implementation on PDP 7.
   BCPL & B = ``typeless''
  
---Slide 2---
 History of C
C, designed by Dennis Ritchie.
 ANSI C, (1983-1988)
---Slide 3---
 SYNTAX
 <type-name> <name> { ',' <name> } ';'
 <name>s separated by commas and terminated by a
  semicolon.
int i,j; int A[3], B[5][7]; int *p; /* pointer to an integer*/
---Slide 4---
 SYNTAX
 <result-type> <name>(<formal-pars>){
    <declaration-list>
    <statement-list>
 }
 <formal-pars>  
 <result-type>int
 main(){}        ===       int main(void){
                             return 0;
                           }
 
void' indicates that a ``function'' is a proper
procedure with no result.
---Slide 5---
 Assignment Operator
C expression.
<expression-1> = <expression-2>
<expression-2> is put in the location
given by the  L-Value of <expression-1>.
  c = getchar();
  while((c = getchar()) != EOF)
    putchar(c);
  for(A[0] = X, i = n; X != A[i]; --i);
  return i;
---Slide 6---
 Syntax of Statements
<stmt-list> ::= <empty> | <stmt-list> <statement>
<statement> ::=
   ;
 | <expression>;
 | {<stmt-list>}
 | if(<expression>)<statement>
 | if(<expression>)<statement> else <statement>
 | while(<expression>) <statement>
 | do <statement> while (<expression>)
 | for(<opt-exp>;<opt-exp>;<opt-exp>)<statement>
 | switch (<expression>) <statement>
 | case <const-exp> : <statement>
 | default : <statement>
 | break;
 | continue;
 | return;
 | return <expression>;
 | goto <label-name>;
 | <label-name> : <statement>;
---Slide 7---
 Control Structure
 {
   x = y = z = 0;
   i++;
   printf(...);
   i = x;
 }
{ and } group declarations and statements into a
block.
 if(n > 0)
   if(a > b)
     z = a;
   else
     z = b;
Dangling else is resolved by associating the else with
the closest previous else-less if.
---Slide 8---
 Control Structure
else if
  if(x == 0)
    y = 'a';
  else if(x == 1) 
    y = 'b';
  else if(x == 2)
    y = 'c';
  else if(x == 3)
    y = 'd';
  else
    y = 'z';
switch
 c = getchar();
 switch(c){
 case '0': case '1': case '2': case '3': case '4':
 case '5': case '6': case '7': case '8': case '9':
    ndigit[c - '0']++;
    break;
 case ' ': case '\n': case '\t':
    nwhite++;
    break;
 default:
    nother++;
    break;
 }
---Slide 9---
 Iterative Statement
while & for
 A[0] = X;                   for(A[0] = X, i =n;
 i = n;                           X != A[i]; --i)
 while(X != A[i])               ;
   --i;                      return i;
 return i;
                A[0] = x;
                i = n;
                for(;;){
                  if(X == A[i]){
                     return i; break;
                  }
                  --i;
                }
---Slide 10---
 break, continue & goto
break causes the innermost enclosing loop or
switch to be exited immediately.
continue statement causes the next iteration of the
innermost enclosing loop to begin
 while & do: The test part is executed
immediately.
  for: The increment step is executed immediately.
 
goto interrupts normal control flow. goto L
causes the control to go to the statement labeled L.
---Slide 11---
 Examples of break & continue
 for(i = 0; i < n; i++){       for(i = 0; i < n; i++){
   if(a[i] < 0)                  if(a[i] < 0)
     break;                        continue;
   ...                           ...
 }                             }
       for(;;c = getchar()){
         if(c == ' '||c == '\t')
           continue;
         if(c != '\n')
           break;
         ++lineno;
       }
Skips over blanks, tabs & newlines, while keeping track of line numbers.
---Slide 12---
 Program Structure
C is  Block-Structured
   {
     <declaration-list>
     <statement-list>
   }
 
C program consists of global declarations of:
---Slide 13---
 Scope in C
C is statically scopedX in a block is  i) that block
  +  ii) all its nested blocks -  iii) all the nested
  blocks in which X is redeclared.
     int main(void)
    |{
    |    int i;         /* Scope of i = */
    |    for( ... )     /*  A + B - C - D */ 
    |  | {
    |  |  int c;
    |  |  if( ... )
    |  |    |{
    | B|  C |  int i;  /* Scope of i =  */
  A |  |    |  ...     /*    C          */
    |  |    |}
    |  |  ...
    |  | }
    |    while( ... )
    |  | {
    | D|   int i;      /* Scope of i =  */
    |  |   ...         /*    D          */ 
    |  | }
    |   ...
    |}
---Slide 14---
 Automatic and External Variables
Or directly by name, if they are explicitly redefined as
extern's.
extern variables are globally accessible and remain in
existence permanently.
 int getline(char line[], int maxline);
 main(){...
   char line[MAXLINE];
   ...
   getline(line, MAXLINE);
 }
 int getline(char s[], int lim){
     ...
 }
---Slide 15---
 Usage of extern: Example
    char line[MAXLINE];
    ...
    int getline(void);
    main(){...
       extern char line[];
        ...
       getline();
       ...
    }
    int getline(void){...
       extern char line[];
       ...
    }
extern declarations are
collected in a ``header'' file, and included by ``#include''
(compiler declarative) in each source file.
---Slide 16---
 Static Variables
Provides a way to hide information
   static char buf[BUFSIZE];
   static int bufp = 0;
   int getch(void{...}
   void ungetch(int c){...}
buf & bufp can be shared by getch &
ungetch. But  not visible to the user of getch &
ungetch
---Slide 17---
 Static Variables
But they remain in existence from one activation to the next.
---Slide 18---
 Types

( The size of Integers and floating points are implementation-defined.)
---Slide 19---
 Types (contd)
+ (Addition), - (Subtraction),* (Multiplication), / (Division), % (Modulus)---Cannot be applied to float or double.
>, >=, <, <=,==, !=,  

---Slide 20---
 Types: Constants

  enum boolean {NO, YES};
  enum escapes {BELL = '\a', BACKSPACE = '\b',
                TAB = '\t', NEWLINE = '\n',
                VTAB = '\v', RETURN = '\r'};
  enum months  {JAN = 1, FEB, MAR, APR, MAY, JUN,
                JUL, AUG, SEP, OCT, NOV, DEC};
---Slide 21---
 TYPE CONVERSION
float f; int i; f + i /* converted into float */
char c; int i; i = c; c = i; /* No information loss */ c = i; i = c; /* Higher order bits--lost */
(<type-name>)<expression> int n; double a; a = sqrt((double) n);
---Slide 22---
 Composite Types: Arrays & Pointers
<type> <name>[<size>]Defines an array (
<name>) of size = <size> with entries
of type = <type>.
Entries are numbered from 0 to  .
.
int a[10]; \* a[0], a[1], ..., a[9] *\
    & = referencing operator, and
    * = dereferencing operator
    int x, y, a[10];
    int *ip, *pa;
    ip = &x; y = *ip; pa = &a[0];
    y = *(pa + 3);
 Note: *(pa + 3)  
 a[3]
---Slide 23---
 Multidimensional Arrays
  int daytab[2][13] = {
      {0,31,28,31,30,31,30,31,31,30,31,30,31},
      {0,31,28,31,30,31,30,31,31,30,31,30,31}
  };
  int leap; int days;
  leap = year%4 == 0;
  days = daytab[leap][i];/* Not daytab[leap,i] */
       A two-dimensional array is really a one dimensional array,
     each of whose element is an array.
int a[10][20]; int *b[10];Note:
a[3][4] and b[3][4] are syntactically
legal.
a = a true 2D array: 200 int-sized locations have been
set aside.
b = a 1D array of pointers: the pointers are not initialized.
---Slide 24---
 Strings
chars
 "I am a string" "A"
char amessage[] = "now is the time"; char *pmessage = "now is the time";Note:
pmessage is a pointer to a character array.
t to s
  void strcpy(char *s, char *t){
     while((*s++ = *t++) != '\0');
  }
---Slide 25---
 Structures
struct =
	Similar to PASCAL record.
  struct point{  /* point is a structure tag */
    int x;
    int y;
  };             /* x, y = members */
  struct point maxpt = {320, 320};
    <structure-name>.<member>
    dist = sqrt((double) pt.x * pt.x
                  + (double) pt.y * pt.y);
---Slide 26---
 Union
union may hold objects of different types and sizes.
    union u-tag{
      int   ival;
      float fval;
      char  *sval;
    } u;
u can be of type int, float or a
	char-pointer.
---Slide 27---
 Type Abstraction
C provides a facility called typedef for
	creating new data type names.
    typedef int  Length;
    typedef char *String;
    Length len; String lineptr[MAXLINES];
C uses structural equivalence---structs, unions and enums with
	 distinct tags are  distinct.
---Slide 28---
 Procedure Declarations
  <result-type> <name> (<formal-pars>){
    <declaration-list>
    <statement-list>
  }
  int succ(int i){
    return (i+1)%size;
  }
int.
void indicates a proper procedure with no
result.
C uses  call-by-value for parameter passing.
Call-by-reference can be simulated by calling with pointers.
---Slide 29---
 Parameter Passing in C
  void bad-swap(int x, int y){
     int z;
     z = x; x = y; y = z;
  }
  int a = 0; int b = 1;
  bad-swap(a, b);
  void swap(int *px, int *py){
     int z;
     z = *px; *px = *py; *py = z;
  }
  int a = 0; int b = 1;
  swap(&a, &b);
---Last Slide---
 Summary
 
 C Design
[End of Lecture #4]