Вы находитесь на странице: 1из 10

Chapter 6] Function

[Def.]A function is a self contained block of statements that perform a coherent task of some kind. Using a function is something like hiring a person to do a specific job for you. The basic philosophy of function is divide and con uer by !hich a complicated tasks are successively divided into simpler and more manageable tasks !hich can be easily handled. A program can be divided into smaller subprograms that can be developed and tested successfully. A function is a complete and independent program !hich is used "or invoked# by the main program or other subprograms. A function can be thought of as a black bo$ that takes one or more input arguments and produces a single output value.

There are many advantages in using functions in a program they are: %t facilitates top do!n modular programming. %n this programming style& the high level logic of the overall problem is solved first !hile the details of each lo!er level functions is addressed later. The length of the source program can be reduced by using functions at appropriate places. This factor is critical !ith microcomputers !here memory space is limited. %t is easy to locate and isolate a faulty function for further investigation. A function may be used by many other programs this means that a c programmer can build on !hat others have already done& instead of starting from scratch. A program can be used to avoid re!riting the same se uence of code at t!o or more locations in a program. This is especially useful if the code involved is long or complicated.

'rogramming teams does a large percentage of programming. %f the program is divided into subprograms& each subprogram can be !ritten by one or t!o team members of the team rather than having the !hole team to !ork on the comple$ program.

Note: ( support the use of library functions and use defined functions. The library functions are used to carry out a number of commonly used operations or calculations. The user)defined functions are !ritten by the programmer to carry out various individual tasks. Functions are used in c for the following reasons: *. +any programs re uire that a specific function is repeated many times instead of !riting the function code as many timers as it is re uired !e can !rite it as a single function and access the same function again and again as many times as it is re uired. ,. -e can avoid !riting redundant program code of some instructions again and again. .. 'rograms !ith using functions are compact / easy to understand. 0. Testing and correcting errors is easy because errors are locali1ed and corrected. 2. -e can understand the flo! of program& and its code easily since the readability is enhanced !hile using the functions. 3. A single function !ritten in a program can also be used in other programs also. C functions can be classified into two categories: *. 4ibrary functions 4ibrary functions are not re uired to be !ritten by user. printf"#&scanf"#&s rt"#&strcat"# etc. are e$amples of library functions. ,. User defined functions User defined function has to be developed by the user at the time of !riting a program. main"# is an e$ample of user)defined functions. Function Prototype

*. ,. ..

4ike other identifiers in (& a function must be declared before it can be used in a program. To do this& you can add a function prototype before main to tell the compiler !hat functions you are planning to use. A function prototype tells the ( compiler5 The data type the function !ill return 6or e$ample& the s rt function returns a type of double. The function name %nformation about the arguments that the function e$pects. The s rt function e$pects a double argument. 7o the function prototype for s rt

!ould be5 double s rt"double#8 void instruct(void ! is a void function void function " does not return a value The function just does something !ithout communicating anything back to its caller. %f the arguments are void as !ell& it means the function doesn9t take any arguments. :o!& !e can understand !hat our main function means5 int main"void# This means that the function main takes no arguments& and returns an int Function definition: A function definition also kno!n as function implementation shall include the follo!ing elements. *. 6unction type ,. 6unction :ame .. 4ist of parameters 0. 4ocal variable declarations 2. 6unction 7tatement 3. A return statement All the si$ elements are grouped into t!o parts& namely& *. 6unction header [ 6irst three elements] ,. 6unction ;ody [ 7econd three elements]

A general format of a function is5 function#type function#name(parameter list $ local variable declaration! e%ecutable statement &! e%ecutable statement '! e%ecutable statement (! ))))** ))))** return statement! + The first line function<type function<name"parameter list# is kno!n as the function header and the statements !ithin the =pening and closing braces constitute the function body& !hich is a compound statement. Function ,eader The function header consists of three parts5 *. The function type also kno!n as return type ,. The function name .. The formal parameter list :ote5 A semicolon is not used at the end of the function header. &* The function Type: The function type specifies the type of value that the function is e$pected to return to the program calling the function. %f the return type is not e$plicitly specified then ( !ill assume that it is an integer type. %f the function is not returning anything& then !e need to specify the return type as void* -oid is one of the fundamental data types in C* The value returned is the output produced by the function.

'* The Function Name (* Note: The parameters used in prototypes and function definitions are called formal 'arameters. .%ample: int sum(int a/ int b $ **** **** + The declaration of parameter variables cannot be combined. i.e. int sum"int a&b# is illegal. A function need not al!ays receive values from the calling program. %n such cases& function have no formal parameters. To indicate that the parameter list is empty& !e use the key!ord void as follo!s5 void message"void# > The function name is any valid ( identifier. %t must follo! the same rules of formation as other variable names in (. The name should be appropriate to the task performed by the function. (are must be taken to avoid duplicating library routine names or =.7. commands. Formal parameter list The parameter list declares the variables that !ill receive the data sent by the calling program. They serve as the input data to the function to carry out the specific task. 7ince they represent actual input values& they are often referred to as formal parameters. These parameters can also be used to send values to the calling programs. The parameters are also kno!n as arguments. The parameter list contains declaration of variables separated by commas and surrounded by parentheses.

...... ? This function neither receives any input values nor returns back any value. +any compilers accept empty parentheses !ithout specifying anything like5 void message"# @$ample 5 mul"a&b# int a&b8 > int y8 yAaBb8 return y8 ? -hen the value of y !hich is the addition of the values of a and b. the last t!o statements ie& yAaBb8 can be combined as return"y# return"aBb#8 Function 0ody The function body contains the declarations and statements necessary for performing the re uired task. The body enclosed in braces & contains three parts in the order given belo!. *. 4ocal declarations that specify the variables needed by the function. ,. 6unction statements that perform the task of the function. .. A return statement that returns the value evaluated by the function. %f a function does not return any value &!e can omit the return statement. :ote that its return type should be specified as void. 1ome e%amples of typical function definition: & Float mul(float %/ float y $ float result! 22local variable

result 3 % 4 y return (result ! + ' void sum (int a/ int b $

22computes the product 22 returns the result

printf(5sum3 6d7/ a8b ! return! + ( void display (void $

22 No local variables 22 9ptional

22No local variables printf(5No type/ No parameters7 22No return statement + -hen a function reaches its return statement& the control is transferred to back to the calling program. %n the absence of a return statement& the closing brace acts like a void return. :include;stdio*h< :include;conio*h< void message( ! void main( $ message( ! + void message( $ printf(5=n,ave a nice day7 ! + 22 function call printf(5=n,ello>7 ! 22 function prototype declaration

9utput is: ,ave a nice day ,ello> Cere& !e have defined t!o functions5 main"# and message" #. -e have used the !ord message at three places in the program. The first is the function prototype and is !ritten as5 void message( ! This indicates that message"# is a function does not return anything after completing its e$ecution. DThis does not return anything9 is indicated using the key!ord void ?t is necessary to mention the prototype of every function that we have defined in the program* The second usage of message is void message( $ printf(5=n,ave a nice day7 ! + This is the function definition. -e can also use if& for !hile& s!itch etc. !ithin this function definition. The third usage of message is message"#8 Cere& the function message"# is being called by main"#. Thus& main"# becomes the EcallingF function !hereas message"# becomes the EcalledF function. :include;stdio*h< :include;conio*h< void italy( ! void bra@il( ! void argentina( ! void main(

$ clrscr( ! printf(5=n ? am in main7 ! italy( ! bra@il( ! argentina( ! getch( ! + void italy( $ printf(5=n ? am in italy7 ! + void bra@il( $ printf(5=n ? am in bra@il7 ! + void argentina( $ printf(5=n ? am in argentina7 ! *. A ( program is a collection of one or more functions. ,. %f a ( program contains only one function & it must be main"#. .. %f a ( program contains more than one function then one and only one of these 0. functions must be main"#& because ( program e$ecution al!ays begins !ith main"#. 2. There is no limit on the number of functions that might be present in a ( program. 3. @ach function in a main program is called in the se uence specified by the function calls in main"#. G. After each function has done its task& control returns to main"#. -hen main"# runs out of statements and function calls& the program ends. H. 'assing values bet!een functions I. The mechanism used to convey information to the function is the argument.

*J. The arguments in the printf"# and scanf"# are the format string and the list of variables inside the parentheses. KK 7ending and receiving values bet!een functions LincludeMstdio.hN LincludeMconio.hN int calsum"int $&int y& int 1#8 KK 6unction 'rototype Ooid main"# > int a& b& c& sum8 printf"@nter any three numbersF#8 sumAcalsum"a& b& c#8 printf"EPnsumAQdF& sum#8 ? int calsum"int $& int y& int 1# > int d8 dA$ByB18 return"d#8 ? @nter any three numbers scanf"EPnQd Qd QdF& /a& /b& /c#8 *J ,J .J sumA3J

Вам также может понравиться