CS31011 Programming Languages C Lecture 3 - PowerPoint PPT Presentation

1 / 66
About This Presentation
Title:

CS31011 Programming Languages C Lecture 3

Description:

Do not let me fail to repeat Qs. Remind me if I forget. Win valuable prizes. 9/24/09 ... ternary op. Dig char int. 9/24/09. CS3101-1, Lecture 3. 20. Ftn e.g. 2: calc.c ... – PowerPoint PPT presentation

Number of Views:40
Avg rating:3.0/5.0
Slides: 67
Provided by: pagesSt
Category:

less

Transcript and Presenter's Notes

Title: CS31011 Programming Languages C Lecture 3


1
CS3101-1Programming Languages CLecture 3
  • Matthew P. Johnson
  • Columbia University
  • Fall 2003

2
Important Reminder
  • Do not let me fail to repeat Qs
  • Remind me if I forget
  • ? Win valuable prizes

3
Agenda
  • Hw1 due last night
  • Hw2 assigned tonight
  • Last time most simple lang features
  • This time Program Structure
  • I/O error-checking
  • complex programs
  • mult ftns, mult files
  • Headers
  • preprocessor
  • vars scope
  • macros
  • make files
  • Recursion

4
I/O error-handing
  • May have noticed
  • Bad results for scanf on bad data abc35efg
  • Fails to read val
  • May lead to inf loop
  • Two simple tips to improve robustness
  • Check return val of scanf
  • Val of vals successfully input, or EOF (-1)
    for some errors
  • If val is lt of vals you expected, somethings
    wrong
  • After input (successful or not), flush stream
  • scanf(d, i) / 12abc put in /
  • fflush(stdin)
  • 12 is read the rest goes away

5
I/O error-handling e.g
  • input2.c
  • include ltstdio.hgt
  • main()
  • int res, i
  • do
  • printf("\n\nenter val ")
  • res scanf("d", i)
  • printf("\nresult d\n", res)
  • if (res 1)
  • printf("val is d", i)
  • fflush(stdin)
  • printf("val is d", i)
  • while (res ! EOF)

6
Complex programsMultiple ftns
  • So far mostly just main()
  • Real programs have multiple ftns
  • In theory, could have 1 monster ftn
  • Better design modular
  • Debugging
  • Maintenance
  • Indy ftns tested indly

7
Multiple files
  • Benefits
  • Team programming
  • Share common code
  • Code-reuse
  • Third-party libraries

8
Function definitions
  • Review general form
  • return-type function-name(arg- declars)
  • declarations
  • statements
  • Return-type
  • Prim/non-prim data type
  • Sort of val returned
  • Void if no return val
  • Ftn has 0 1 return val
  • For mult changes, can use
  • Globals (later) or
  • Pointers (next time)

9
Function definitions
  • Ftn-name
  • Case-sens
  • Alpha-num (with _)
  • Starts with alpha or _
  • Arg-declars
  • Comma-sep-ed list of decars of args to be passed
  • Body
  • Marked by braces
  • Local vars declared at top of curr block

10
Function definitions
  • Use return
  • to end exec of ftn
  • (perhaps) to return result
  • If no return stmt, exec continues to end of body
  • For void ftn say
  • return
  • For non-void ftn say
  • return expr
  • Val of expr is/converts to return type
  • Use correctly! Little/no error-checking

11
Return vals
  • double square(double val)
  • double sq valval
  • return sq
  • Suppose forgot return line
  • double square(double val)
  • double sq valval
  • ? square(5) ? garbage

12
Return vals
  • Suppose had wrong/missing return type
  • void square(double val)
  • double sq valval
  • return sq
  • ? s square(5) ? garbage

13
Return vals
  • Ftn caller is free to ignore return val of
    non-void ftn
  • square(5)
  • But return type and return value should match!

14
Ftn Declarations
  • Remember should put declar at top
  • double square(double)
  • Arg types must match ftn signature in ftn
    definition (what appears before open brace)
  • Arg names neednt match, can be omitted
  • No ftn overloading in C! (ftn names are unique)

15
Minimal legal ftn
  • ftn()
  • No explicit return type ? int is default (not
    void!)
  • No params can also say
  • ftn(void) for more explicitness

16
Ftn e.g. 1 parsing
  • Goal parse string rep of double support
  • int portion
  • /-
  • ., decimal portion

17
Ftn e.g. 1 conv.c
  • / no includes
  • no main
  • atof() appears in stdlib.h
  • atof array to floating-point /
  • double myatof(char s)
  • double val, power, exp
  • int i,sign
  • for(i0 isspace(si) i)
  • sign (si'-') ? -1 1
  • if (si'' si'-')
  • i

18
Ftn e.g. 1 conv.c
  • for (val0.0 isdigit(si)i)
  • val 10.0val (si-'0')
  • if (si '.')
  • i
  • for (power1.0 isdigit(si) i)
  • val 10.0val (si-'0')
  • power 10
  • return sign val / power

19
Ftn e.g. 1 conv.c
  • Things to notice
  • Body-less for-loop
  • ? ternary op
  • Dig char ? int

20
Ftn e.g. 2 calc.c
  • Goal program repeatedly inputs decimal num
    reports current total
  • Use myatof as subroutine
  • include ltstdio.hgt
  • define MAXLINE 100
  • main()
  • double sum //, myatof(char)
  • char lineMAXLINE
  • int count 0

21
Ftn e.g. 2 calc.c
  • sum 0
  • while (count lt 10)
  • char lineMAXLINE
  • scanf("s", line)
  • printf("\nsum is lf\n", sum
    myatof(line))
  • count
  • return 0

22
Ftn e.g. 2 calc.c
  • Compile two files to exec
  • List source files sep-ed by spaces
  • gcc calc.c conv.c
  • When run, what happens?
  • ? prints garbage why?
  • Reason myatof not declared before use
  • ? assumes default ftn (return type int)

23
Libraries Using libs
  • Soln 1 declare locally before use
  • Add double myatof(char) to calc.cs main() or
    top of calc.c
  • Pro works
  • Con awkard
  • Must declare each ftn used from lib
  • Must declare in each local ftn/file

24
Using libraries
  • Soln 2 use header file
  • Almost every .c file has a corresponding .h file
  • .h usually contains public ftn declars
  • Also constants, types defs, extern var declars
    macros
  • .c contains active code

25
Important built-in libs
  • stdio.h standard I/O
  • stdlib.h standard lib (util ftns)
  • string.h copying strs, etc.
  • ctype.h conv to upper/lower, etc.
  • math.h pow, sqrt, etc.
  • Compile with lm to link
  • View headers
  • /usr/include on cunix

26
conv.h header
  • conv.h
  • double myatof(char s)
  • Now, can include in calc.c
  • include conv.h
  • local libs
  • lt gt system libs
  • Now, calc.c can see any other ftns in .h

27
Using libraries
  • Idea
  • .h header public interface
  • .c source private implementation
  • .h contains what is published about the contents
    of .c (API)
  • .c is the private implementation of public
    methods, private helper methods, etc.
  • Benefit others rely on interface in .h
  • ? can change implementation w/o changing
    interface or dependent code

28
include review
  • Allows access to ftn declared in other file
  • Instrumentally similar to Javas import
  • Different behavior include line is replaced
    with contents of spec-ed file

29
include danger
  • head1.h
  • int ftn()
  • head2.h
  • include head1.h
  • int ftn2()
  • prog.c
  • include head1.h
  • include head2.h

30
include danger
  • prog.c
  • int ftn()
  • include head2.h
  • prog.c
  • int ftn()
  • include head1.h
  • int ftn2()
  • prog.c
  • int ftn()
  • int ftn()
  • int ftn2()
  • ? compiler error
  • ftn() declared twice!

31
include danger soln
  • Soln ensure each header is include lt once
  • Method first time header read, define special
    symbol
  • In future (i.e., if symbol has been defined),
    skim include

32
include danger soln
  • head1.h
  • ifndef _HEAD1_H
  • define _HEAD1_H
  • int ftn()
  • endif

33
include danger soln
  • prog.c
  • include head1.h
  • include head1.h
  • prog.c
  • ifndef _HEAD1_H
  • define _HEAD1_H
  • int ftn()
  • endif
  • include head1.h
  • prog.c
  • define _HEAD1_H
  • int ftn()
  • include head1.h
  • prog.c
  • define _HEAD1_H
  • int ftn()
  • ifndef _HEAD1_H
  • define _HEAD1_H
  • int ftn()
  • endif
  • prog.c
  • define _HEAD1_H
  • int ftn()

34
C Preprocessor
  • Unnec use of CPP frowned upon by some
  • often can replace CPP code with C code (enum,
    const, etc.)
  • Included for historical reasons
  • usually located only
  • in .h files (apart from includes)
  • for OS-specific code

35
CPP commands
  • Conditional if, else, endif, elif
  • of course, if expr must be const exprs
  • NB no braces
  • if/else bodies delimited by CPP cmds
  • Defining define, ifdef, ifndef, undef
  • most common uses
  • toggle between OSs
  • toggle between debug/release

36
CPP OS-toggling
  • define UNIX 3
  • define WINDOWS 1
  • define MAC 2
  • define OPSYS abc
  • ...
  • if OPSYS WINDOWS
  • printf("do windows stuff\n")
  • elif OPSYS UNIX
  • printf("do unix stuff\n")
  • elif OPSYS MAC
  • printf("do mac stuff\n")
  • else
  • printf("unknown os\n")
  • endif
  • Tip dont define sym to be 0
  • Attempt to compare sym to invalid val (OPSYS 0
    ? abc 0) may eval as true
  • E.g. preproc2.c

37
CPP debug-toggling
  • ifdef DEBUG
  • printf("current val d\n", x)
  • endif
  • benefit of debug-toggling
  • For testing, includes helpful debug info
  • For final/release, no wasted space
  • debug-toggling makes clear CPP/C distinction
  • 2 sep steps analogous to, e.g., JavaScript HTML
  • first, JavaScript portion is eval-ed and produces
    html code
  • second, resulting html code is eval-ed and
    displayed
  • also, XSLT/XML, etc.
  • E.g. preproc.c

38
Vars scope external vars
  • Var is
  • internal (local) if defined in a ftn
  • external (global), o.w.
  • External vars are visible from other files
  • Unlike automatic (local) vars, ext vars keep val
    through life of program
  • Similar to public static vars in Java
  • Can see CPP output with E option
  • E.g. preproc2.txt

39
Scope
  • Every var has some scope area from which it is
    visible (in scope)
  • Determines which, if any, var your use of an id
    refers to
  • Scope rules
  • Ftn args local vars have score of the ftn in
    which theyre defined
  • int ftn (int a)
  • int b

40
Scope rules
  • 2. More generally, vars declared at top of a
    block have the scope of the block
  • int ftn (int a)
  • int b
  • if (a 1)
  • int a
  • else
  • int d
  • if (a 2)
  • int a
  • d 2

41
Scope rules
  • Ext vars have scope from declaration to bottom of
    file
  • main()
  • int i 10
  • void ftn1() int i 12
  • void ftn2()
  • Global i is in scope in
  • Ftn2, not ftn1, not main
  • Q What if ftn1, ftn2 call one another?
  • One must be defined first
  • A Declare them both above!

42
Scope rules
  • 4. Ext vars can be in scope in other files, if
    declared there
  • prog1.c
  • int i 10 / var definition /
  • prog2.c
  • extern int i / var declaration /
  • Var declarations are similar to ftn declars
    anounce the form of something defined elsewhere
  • If prog1.c, prog2.c linked together, both can
    access i

43
define v. declar
  • define allocates mem for var / ftn
  • declar merely assocs id with type/signature
  • item defined only once
  • can be declar mult times

merely declars extern int x int ftn() extern
int ftn()
declars and defines int x int ftn() ...
declars, defines, AND initializess int x 10
44
Ext define v. ext declar
  • extern is used for the declaration of an extern
    var
  • file-level definition w/o static is automatically
    extern
  • extern distinguishes var define from var declar
  • but extern is optional for ftn declar
  • clear from rather than that it's declar
  • E.g. extern1.c extern2.c

45
Static vars
  • Should not overuse external vars
  • Try to keep code modular
  • Can prevent external use of ftn-level var by
    making var static
  • static int i
  • Other uses of static
  • Static ftns
  • Makes inaccessible
  • Static local vars
  • Retains value between ftn calls
  • Like globals
  • Initialization exec-ed only once
  • Auto-init-ted to 0 if init ommited (like globals)

46
Static local vars
  • Counts times called
  • void num_times()
  • static int count 0
  • / set to 0 only first time! /
  • count
  • printf(count d\n, count)
  • Local static concept ! global static concept !
    Java static concept

47
Register vars
  • Special vars for frequent use
  • register int x
  • int f(register int x)
  • Will place in a machine register if available
  • Otherwise, no effect

48
Automatic vars
  • Name of regular, local or param vars
  • Come into existence on block entry
  • Go away on block exit

49
Macros
  • Already saw symbolic constants
  • define MAX 100
  • Special case of macros
  • Can take params, act like ftns
  • define isupper(c) ((c) gt A \ (c) lt
    Z))
  • Like sym consts, preprocessor does search
    replace before compilation
  • Param id in expr is replaced with arg given
  • isupper(B) ? ((B) gt A (B) lt Z))

50
Macro pitfalls
  • Precedence
  • define square(x) xx
  • square(23) ? 2323 11 ! 25
  • define double(x) xx
  • double(3)double(2) ? 3322
  • Soln use parens around each var and around
    entire replace-expr
  • define square(x) ((x) (x))

51
Macro pitfalls
  • 2. Side effects
  • square(i) ? ((i)(i))
  • Result i ? i2
  • (Possible) inefficiency
  • square(allday(10)) ? ((allday(10))(allday(10)))
  • Idea the allday() ftn takes all day to run
  • No general soln

52
Macro benefits
  • Can be very efficient
  • No overhead on stack!, just eval
  • Char I/O routines often actually macros
  • Used for short, oft-called ftns
  • Can simplify type issues
  • Suppose want max ftn
  • type ftn(type a, type b)
  • return a gt b ? a b
  • What is type?

53
Macros types
  • Soln 1 make all doubles
  • Okay if assigned to var
  • Val will be truncated
  • int i max(2,3)
  • ? 3.0 ? 3
  • But trouble for I/O
  • printf(max d\n, max(1,2))
  • Wildcard must now be lf

54
Macros types
  • Soln 2 use a macro
  • define max(a,b) ((a) gt (b) \ ? (a) (b))
  • Now type of max(a,b) is widest of the types of a
    and b
  • max(2,3) ? 3
  • max(1.5, 2.5) ? 2.5

55
Macros
  • Notice
  • no required
  • Preprocessor commands do not end w/
  • A ftn/macro call is an expr, perhaps a sub-expr
  • x square(a) square(b)
  • Dont want a in the expansion of square(a)
  • use \ to span macro def over mult lines
  • To delete macro
  • undef square

56
Make files
  • Defines script for compiling project
  • Convenient
  • Only compiles what has changed/must be compiled
  • 4 main ideas
  • comments 1-line, begins with
  • macros CC gcc
  • explicit rules run arbitrary cmds
  • Wont cover
  • implicit rules for dependencies (most important)
  • target target-name depend1, depend2, ...

57
Make files
  • Example
  • comp
  • CC gcc
  • comp flags
  • CFLAGS -Wall g
  • var for exec list
  • EXECS calc2

58
Make files
  • define target for all default
  • all EXECS
  • lib recipes
  • conv.o conv.c conv.h
  • calc2.o conv.h calc2.c
  • exec recipes
  • calc2 conv.o calc2.o
  • clean target
  • clean rm f core EXECS

59
Make file dependencies
  • Idea list all the immediate dependencies of the
    target
  • dependency means if its updated then target
    must be updated e.g. objects source file, an
    included header file, etc.
  • Update recognized by difference of timestamps
  • Dependency tree traversed recursively
  • E.g Makefile

60
Make files- notice
  • Everything assumed to be one line
  • Use \ to continue (as with CPP)
  • Case-sensitive
  • Many built-in vars CC
  • do make -p more to see
  • Use VAR to refer to get val of VAR
  • A target is like a ftn call
  • make clean
  • Default target is all
  • Default make filename is Makefile (no extension)
  • Specify other filename with make f filename
  • Be careful make-file writing can be harder than
    C programming
  • Little feedback
  • Errors from missing/extra spaces, tabs
  • For must purposes, can modify existing makefiles

61
Recursion
  • Suppose want to compute power ftn bexp.
  • Could write iteratively
  • int power(int base, int exp)
  • int res 1
  • for ( exp gt 0 exp--)
  • res base
  • return res

62
Recursion
  • Could also write recursively
  • int power(int base, int exp)
  • if (exp 0)
  • return 1
  • return base power(base, --exp)
  • Better worse?
  • x0 1 00
  • Elegant logic is implicit (in program
    structure), not explicit (in lines of code)
  • Save local var
  • But more mem used base,exp insts for each level
  • Pass-by-value!

63
Iterative stack
  • Suppose call val power(3,2)
  • Iteratively
  • NB params usually allocate backwards

64
Recursive stack
  • Much more memory!

65
Recursive stack
66
Next time
  • Next time pointers arrays
  • Hw2 assigned tonight
  • Reading on web
  • Come to OHs if nec!
  • Sign in!
Write a Comment
User Comments (0)
About PowerShow.com