CS 192 - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

CS 192

Description:

... to calling function when return encountered or closing curly brace of function ... Don't necessarily have to store the returned value in a variable #include ... – PowerPoint PPT presentation

Number of Views:21
Avg rating:3.0/5.0
Slides: 34
Provided by: Sham4
Category:

less

Transcript and Presenter's Notes

Title: CS 192


1
CS 192
  • Lecture 14
  • Winter 2003
  • January 14-15, 2004
  • Dr. Shafay Shamail

2
Functions
  • Building blocks of a C program
  • Each function has a name, which is used to call
    the function functions call each other
  • You will write your own functions, e.g. main(),
    and also use pre-written functions from standard
    library

3
  • / This program contains two functions main()
  • and myfunc().
  • /
  • include ltiostream.hgt
  • void myfunc() // myfunc's Protoype
  • int main()
  • cout ltlt "In main()"
  • myfunc() // call myfunc()
  • cout ltlt "Back in main()"
  • return 0
  • void myfunc() // myfuncs Definition
  • cout ltlt " Inside myfunc() "

4
Function Prototype
  • void myfunc() // myfunc's Protoype
  • Like variable declaration tells the compiler
    about the return type of the function and the
    number and type of parameters it needs from the
    calling function
  • return_type functionName (parameter list)
  • So, place prototypes before main()
  • main() is predefined in C and does not need a
    prototype
  • Cant the compiler look ahead and get
    definitions?
  • Prototype can be omitted if whole function placed
    before it is called is that a good practice?

5
Returning a Value
  • // Returning a value.
  • include ltiostream.hgt
  • int mul(int x, int y) // mul()'s prototype
  • int main()
  • int answer
  • answer mul(10, 11) // assign return value
  • cout ltlt "The answer is " ltlt answer
  • return 0
  • // This function returns a value.
  • int mul(int x, int y)
  • return x y // return product of x and y

6
Library Functions
  • Pre-written functions in libraries that you can
    use
  • Just include the proper header file
  • Compiler gets prototype from the header file and
    searches appropriate libraries itself to get
    function definition
  • e.g. math library has mathematical functions in
    it
  • include ltiostream.hgt
  • include ltmath.hgt //or ltcmathgt
  • int main()
  • cout ltlt sqrt(9.0)
  • return 0

7
Scope Rules
  • Scope rules tell that a variable is visible to
    which parts of your program also define
    variables lifetime
  • 3 types of variables local, global, formal
    parameters

8
Scope Rules - Local Variables
  • A variable can be declared inside any block and
    is then local to that block
  • Block
  • int main()
  • int x 4
  • cout ltlt x
  • return 0
  • error C2065 'x' undeclared identifier
  • Memory storage for a local variable created when
    entering its block and destroyed when its block
    exited

9
Scope Rules-Local Variables
  • Most common block is a function
  • include ltiostream.hgt
  • void func()
  • int main()
  • int x // local to main()
  • x 10
  • func()
  • cout ltlt x // displays ?
  • return 0
  • void func()
  • int x // local to func()
  • x -199
  • cout ltlt x // displays ?
  • -199 10. Each variable x has a separate location
    in memory
  • Identically-named variables in inner block hide
    or override those in the outer block Avoid this
    practice

10
Scope Rules-Local Variables
  • include ltiostream.hgt
  • int main()
  • int i, j
  • i 10
  • j 100
  • if(j gt 0)
  • // start of block
  • int i // this i is separate from outer i
  • i j / 2 // outer j is known here
  • cout ltlt first inner i " ltlt i ltlt '\n'
  • if(i lt 50)
  • i 10 cout ltlt 2nd inner i ltlt i ltlt
    endl
  • cout ltlt "outer i " ltlt i ltlt '\n'
  • return 0

11
Scope Rules-Local Variables
  • int main()
  • int choice
  • cout ltlt "(1) add numbers or "
  • cout ltlt "(2) concatenate strings? "
  • cin gtgt choice
  • if(choice 1)
  • int a, b / activate two integer vars /
  • cout ltlt "Enter two numbers "
  • cin gtgt a gtgt b
  • cout ltlt "Sum is " ltlt ab ltlt '\n'
  • else
  • char s180, s280 / activate two
    strings /
  • cout ltlt "Enter two strings "
  • cin gtgt s1

12
Scope Rules-Local Variables
  • Variables declared in for loops are local
    according to current spec for C
  • for(int i 0 ilt10 i)
  • cout ltlt i ltlt " "
  • i 100 // Error -- i not known here!
  • Does not work on Visual C 6.0 (i.e. no error)
  • Can declare a variable within any conditional
    expression
  • if(int x 20)
  • cout ltlt "This is x "
  • cout ltlt x
  • x 2 // Error -- x not known here!
  • Not a good practice

13
Scope Rules-Formal Parameters
  • Formal parameters variables that receive values
    passed to a function
  • Scope local to the function
  • include ltiostream.hgt
  • int mult(int, int)
  • int main()
  • int a 10, b 20
  • cout ltlt mult(a, b)
  • //cout ltlt x ltlt y // Error --unknown
    identifiers x, y
  • return 0
  • int mult(int x, int y)// can have different
    names here
  • return xy

14
Scope Rules-Global Variables
  • Usually declared outside any function have life
    as long as the program runs
  • Can be used by all following functions
  • Usually placed at the beginning of program
  • Initialized only at the start of the program
    uninitialized default to zero
  • An identically named local variable masks global
    one

15
Scope Rules-Global Variables
  • include ltiostream.hgt
  • void func()
  • int i 2 // global
  • int main()
  • cout ltlt i ltlt endl
  • func()
  • cout ltlt i ltlt endl
  • int i 5 // local. What if i5
  • cout ltlt i ltlt endl
  • func()
  • return 0
  • void func()
  • cout ltlt i ltlt endl
  • int i 3 // local
  • cout ltlt i ltlt endl

16
Scope Rules-global variables
  • include ltiostream.hgt
  • include ltcstdlibgt
  • void drill()
  • int count //count and num_right are global
  • int num_right
  • int main()
  • cout ltlt "How many practice problems "
  • cin gtgt count
  • num_right 0
  • do
  • drill()
  • count--
  • while(count)
  • cout ltlt "You got " ltlt num_right ltlt
  • right.\n"
  • return 0
  • void drill()
  • int count / This count is local. /
  • int a, b, ans
  • // Generate two numbers between 0 and 99.
  • a rand() 100
  • b rand() 100
  • // The user gets three tries to get it right.
  • for(count0 countlt3 count)
  • cout ltlt "What is " ltlt a ltlt " " ltlt b ltlt "?
    "
  • cin gtgt ans
  • if(ansab)
  • cout ltlt "Right\n"
  • num_right
  • return
  • cout ltlt "You've used up all your tries.\n"

17
Passing Pointers to Functions
  • No big deal. Just declare parameter as type
    _______ ?
  • include ltiostream.hgt
  • void f(int j)//or void f(int )
  • int main()
  • int i
  • int p
  • p i // p now points to i
  • f(p)
  • cout ltlt i // i is now 100
  • return 0
  • void f(int j)
  • j 100 // var pointed to by j is assigned
    100

18
Passing Pointers to Functions
  • The pointer variable not necessary. Can generate
    and pass the address of i as such to f()
  • include ltiostream.hgt
  • void f(int j)
  • int main()
  • int i
  • f(i)
  • cout ltlt i
  • return 0
  • void f(int j)
  • j 100 // var pointed to by j is assigned
    100

i
26
100
j
100
19
Passing Pointers to Functions
  • include ltiostream.hgt
  • int sqr_it(int x)
  • int main()
  • int t10
  • cout ltlt sqr_it(t) ltlt ' ' ltlt t //output?
  • int sqr_it(int x)
  • x xx
  • return x
  • IMPORTANT Whats the difference between the
    above function, and the ones on previous two
    slides?
  • Here, a copy of the value of t is passed. t
    remains unaltered. x is a local variable, which
    could have been named t
  • Called Call by Value
  • Previous called Call by Reference where the
    original variable (not a copy) is accessed by the
    called function

(copy)
5
x
5
20
Passing Arrays to Functions
  • What is an array name without index?
  • Address of first element passed to function. So
    actual array accessed, not a copy. Saves memory
  • 3 ways to pass this address
  • Declare parameter as an array of same type and
    size
  • include ltiostream.hgt
  • void display(int num10) //or display(int
    10)
  • int main()
  • int t10,i
  • for(i0 ilt10 i) tii
  • display(t) // pass array t to a function
  • cout ltltendl
  • for(i0 ilt10 i) cout ltlt ti ltlt ' '
    //output?
  • // Print some numbers.
  • void display(int num10)
  • int i
  • for(i0 ilt10 i) cout ltlt numi ltlt ' '
    //output?
  • for(i0 ilt10 i) (numi numi 1)

21
Passing Arrays to Functions
  • Can also declare as display(int num) i.e.
    unsized. Same thing
  • Internally, compiler converts int num10 or int
    num to int
  • So, why not declare parameter as a pointer to int
  • void display(int num)
  • int i
  • for(i0 ilt10 i) cout ltlt numi ltlt ' '
    //or (numi)
  • How is a single element passed? As an ordinary
    variable
  • include ltiostream.hgt
  • void display(int num) //each element is of type
    int
  • int main()
  • int t10,i
  • for(i0 ilt10 i) tii
  • for(i0 ilt10 i) display(ti) //only one
    element passed
  • void display(int num)
  • cout ltlt num ltlt ' '

22
Passing Arrays to Functions
  • include ltiostream.hgt
  • void cube(int n, int num)
  • int main()
  • int i, nums10
  • for(i0 ilt10 i) numsi i1
  • cout ltlt "Original contents "
  • for(i0 ilt10 i) cout ltlt numsi ltlt ' '
  • cout ltlt '\n'
  • cube(nums, 10) // compute cubes
  • cout ltlt "Altered contents "
  • for(i0 ilt10 i) cout ltlt numsi ltlt ' '
  • return 0
  • void cube(int n, int num)
  • while(num)
  • n n n n

23
Passing Strings to Functions
  • What is a string stored as? So what should we
    pass?
  • include ltiostream.hgt
  • include ltcstringgt
  • include ltcctypegt
  • void stringupper(char str)
  • int main()
  • char str80
  • strcpy(str, "this is a test")
  • stringupper(str)
  • cout ltlt str // display uppercase string
  • return 0
  • void stringupper(char str)
  • while(str)
  • str toupper(str) // uppercase one char
  • str // move on to next char

24
The return Statement
  • return statement can be used without a value for
    void functions. Must return a value for non-void
    functions
  • Control passed back to calling function when
    return encountered or closing curly brace of
    function
  • include ltiostream.hgt
  • void power(int base, int exp)
  • int main()
  • power(2, 10)
  • return 0
  • void power(int base, int exp)
  • int i
  • if(explt0) return
  • i 1
  • for( exp exp--) i base i
  • cout ltlt "The answer is " ltlt i ltlt endl

25
The return Statement
  • Can have multiple return statements. Function
    returns as soon as the first one encountered
  • void f()
  • // ...
  • switch(c)
  • case 'a' return
  • case 'b' // ...
  • case 'c' return
  • if(countlt100) return
  • // ...

26
The return Statement
  • non-void functions return values to the calling
    function. Therefore, can call a non-void function
    and use that call as an operand in an expression
    (as it has a value) in the calling function
  • x power(y)
  • if(max(x, y)) gt 100) cout ltlt "greater"
  • switch(abs(x)) ...
  • Dont necessarily have to store the returned
    value in a variable
  • include ltiostream.hgt
  • include ltcstdlibgt
  • int main()
  • int i
  • i abs(-10) // stored
  • cout ltlt abs(-23) // just used
  • abs(100) // returned value discarded
  • return 0

27
Multiple return Statements
  • include ltiostream.hgt
  • int find_substr(char sub, char str)
  • int main()
  • int index
  • index find_substr("three", "one two three")
  • cout ltlt "Index of three is " ltlt index //
    index is 8
  • return 0
  • int find_substr(char sub, char str)
  • int t
  • char p, p2
  • for(t0 strt t)
  • p strt // reset pointers
  • p2 sub
  • while(p2 p2p)
  • // check for substring
  • p
  • p2
  • / If at end of p2 (i.e., substring), then a
    match has been found. /
  • if(!p2)
  • return t // return index //of
    match
  • return -1 // no match found

28
Returning Pointers
  • char get_substr(char sub, char str)
  • int t
  • char p, p2, start
  • for(t0 strt t)
  • p strt // reset pointers
  • start p
  • p2 sub
  • while(p2 p2p)
  • //check for substring
  • p
  • p2
  • / If at end of p2 (i.e., substring), then
    a match has been found. /
  • if(!p2)
  • return start / return pointer to
    beginning of substring /
  • include ltiostream.hgt
  • char get_substr(char sub, char str)
  • int main()
  • char substr
  • substr get_substr("three", "one two three
    four")
  • cout ltlt "substring found " ltlt substr
  • return 0

29
Command Line Arguments
  • To pass info to main() from the command line
  • e.g. cl hellouser
  • Here, cl and hellouser are command line
    arguments
  • main() receives infor about these arguments in
    two parameters
  • int main( int argc, char argv)
  • argc (argument count) parameter is an integer
    that holds the number of arguments on the command
    line. Always at least 1, as program name also
    counted
  • argv (argument variable) parameter is a
    null-terminated array of pointers to strings
  • argv0 points to program name on command line,
    argv1 points to the first argument, and so on.
    argvargc0

30
Command Line Arguments
  • include ltiostream.hgt
  • int main(int argc, char argv)
  • if(argc!2)
  • cout ltlt "You forgot to type your name.\n"
  • return 1
  • cout ltlt "Hello " ltlt argv1 ltlt '\n'
  • return 0
  • If we name this program as greeting, then after
    making an exe file we can type greeting Shamail
    at the command prompt and the program will
    execute and output Hello Shamail
  • Spaces and tabs usually separate strings for a
    longer string, use quotes e.g. greeting Shafay
    Shamail outputs Hello Shafay Shamail

31
Command Line Arguments
  • Can access individual characters in the command
    line strings by using a double subscript. See the
    program echo below
  • include ltiostream.hgt
  • int main(int argc, char argv)
  • int t, i
  • for(t0 tltargc t)
  • // t denotes the tth string
  • i 0
  • while(argvti)
  • // ti accesses the ith character of t
  • cout ltlt argvti
  • i
  • cout ltlt ' '
  • cout ltlt ' '
  • return 0

32
Passing Numeric Command Line Arguments
  • Want to pass numbers to main( ), but it takes
    strings
  • Use atof(), atoi(), atol()
  • include ltiostream.hgt
  • include ltcstdlibgt
  • int main(int argc, char argv)
  • double a, b
  • a atof(argv1)
  • b atof(argv2)
  • cout ltlt a b
  • return 0
  • atoi(2) gives 2 atof(-11.11) gives -11.11

33
Command Line Arguments
include ltiostream.hgt int main(int argc, char
argv) while(--argc gt 0) cout ltlt argv
ltlt endl return 0
include ltiostream.hgt int main(int argc, char
argv) for(int j0 jltargc j) cout
ltlt argvj ltlt endl return 0
  • include ltiostream.hgt
  • include ltcstdlibgt
  • int main(int argc, char argv)
  • double a, b
  • a atof(argv1)
  • b atof(argv2)
  • cout ltlt a b
  • return 0

include ltiostream.hgt include ltcstdlibgt int
main(int argc, char argv) char argvector
argv double a, b a atof(argvector)
b atof(argvector) cout ltlt a b
return 0
Write a Comment
User Comments (0)
About PowerShow.com