What is a Function in C?

A function is a block of code that has a name and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required.

Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities – called functions in C – to get its tasks done. A function is a self contained block of statements that perform a coherent task of same kind

The name of the function is unique in a C Program and is Global. It means that a function can be accessed from any location with in a C Program. We pass information to the function called arguments specified when the function is called. And the function either returns some value to the point it was called from or returns nothing.

We can divide a long C program into small blocks which can perform a certain task. A function is a self contained block of statements that perform a coherent task of same kind.

Structure of a Function

There are two main parts of the function. The function header and the function body.

Function Header

In the first line of the above code

int sum(int x, int y)

It has three main parts

  1. The name of the function i.e. sum
  2. The parameters of the function enclosed in parenthesis
  3. Return value type i.e. int

Function Body

What ever is written with in { } in the above example is the body of the function.

Function Prototypes

The prototype of a function provides the basic information about a function which tells the compiler that the function is used correctly or not. It contains the same information as the function header contains. The prototype of the function in the above example would be like

int sum (int x, int y);

The only difference between the header and the prototype is the semicolon ; there must the a semicolon at the end of the prototype.

Functions in C++ Programming

Functions groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities – called functions in C – to get its tasks done. A function is a self contained block of statements that perform a coherent task of same kind. e.g

Simple Functions

Our first example demonstrates a simple function those purpose is to print a line of 45 asterisks.The example program generates a table , and lines of asterisks are used to make the table more readable. Here’s the listing for Table:

The output from the program looks like this

Why we use Functions

The most important reason to use functions is to aid in the conceptual organization of a program.

Another reason to use functions is to reduce program size. Any sequence of instructions that appears in program more than once is a candidate for being made into a function. The function”s code is stored in only one place in memory, even though the function is executed many times in the course of the program.

Two reasons

  1. Writing functions avoids rewriting the same code over and over. Suppose that there is a section of code in a program that calculates area of a triangle. If, later in the program we want to calculate the area of a different triangle we wont like to write the same instructions all over again. Instead we would prefer to jump to a “section of code” that calculates area and then jump back to the place from where you left off. This section of code is nothing but a function.
  2. Using functions it becomes easier to write programs and keep track of what they are doing. If the operation of a program can be divided in to separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separating the code in to modular functions also makes the pro-gram easier to design and understand.

Function Declaration

Just as you can”t use a variable without first telling the compiler what it is, you also can”t use a functions without telling the compiler about it, There are two ways to do this . The approach we show here is to declare the function before it is called. The other approach is to define it before it”s called. ; we”ll examine that next.) in the Table program, the functions starline() is declared in the line.

Void starline ( );

The declaration tells the compiler that at some later point we plan to present a function called starline. The keyword void specifies that the function has no return value, and the empty parentheses indicate that it takes no arguments.

Notice that the function declarations is terminated with a semicolon It is a complete statement in itself.

Function declarations are also called prototypes, since they provide a model or blueprint for the function. They tell the compiler,” a function that looks like this is coming up later in the program, so it”s all right if you see references to it before you see the function itself.”

Calling the Function

The function is called (or invoked) three times from main (). Each of the three calls look like this:

Starline():

This is all we need to call a function name,followed by parentheses. The syntax of the call is very similar to that of declaration, except that the return type is not used. A semicolon terminates the call. Executing the call statement causes the function to execute; that is, control is transferred to the function, the statement in the function definition are executed, and then control returns
to the statement following the function call.

Function Definition

Finally, we come to the functions its self, which is referred to as the functions definition, The definition contains the actual code for the function. Here’s the definition for starline( ) .

The definition consists of a line called the decelerator, followed by the function body , The function body is composed of the statements that make up the function, delimited by braces.

The decelerator must agree with the declaration: It must use the same function name, have the same argument types in the same order( if there are arguments), and have the same return type.

Notice that a semicolon does not terminate the decelerator. Figure shows the syntax of the function declaration, function call, and function definition.

When the function is called, control is transferred to the first statement in the functions body. The other statements in the function body are then executed, and when the closing brace is encountered, control returns to the calling program.

There are basically two types of functions

  1. Library functions Ex. printf ( ), scanf ( ) etc.
  2. User defined function e.g the function message mentioned above.
    The following point must be noted about functions (i) C program is a collection of one or more functions (ii) A function gets called when the function name is followed by a semicolon for e.g.

     

  3. Function is defined when function name is followed by a pair of braces in which one or more statements may be present for e.g.

  4. Any function can be called from any other function even main ( ) can be called from other functions. for e.g.

  5. A function can be called any number of times for eg.

  6. The order in which the functions are defined in a program and the order in which they get called need not necessarily be same for e.g.

  7. A function can call itself such a process as called “recursion”.
  8. A function can be called from other function, but a function cannot be defined in an-other function. These the following program code would be wrong, since Argentina is being defined inside another function

  9. Any C program contains at least one function.
  10. If a program contains only one function, it must be main( ).
  11. In a C program if there are more than one functional present then one of these functional must be main( ) because program execution always begins with main( ).
  12. There is no limit on the number of functions that might be present in a C program.
  13. Each function in a program is called in the sequence specified by the function calls in main( )
  14. After each function has done its thing, control returns to the main( ), when main( ) runs out of function calls, the program ends.

Functions declaration and prototypes Any function by default returns an int value. If we desire that a function should return a value other than an int, then it is necessary to explicitly mention so in the calling functions as well as in the called function. for e.g

The sample run of this program is

Here 6 is not a square of 2.5 this happened because any C function, by default, always returns an integer value. The following program segment illustrates how to make square ( ) capable of returning a float value.

sample run Enter any number 2.5 square of 2.5 is 6.2500000

Passing Arguments to Function

An argument is a piece of data (an into value, for exp) passed from a program to the function. Arguments allow a function to operate with different values, or even to do different things, depending on the requirements of the program calling it.

Passing Constants

As an exp, let”s suppose we decide that the starline ( ) function in the last exp is too rigid. Instead of a function that always prints 45 asterisks, we want a function that will print any character any number of times

Here is a program, tablearg.cpp, that incorporates just such a function. We use arguments to pass the character to be printed and the number of times to print it .

The new function is called repchar ( ), Its declaration looks like this

Void repchar ( char, int); // declaration specifies data types

The items in the parentheses are the data types of the argument that will be sent to repchar( ): char and int.

In a function call, specific values—– constants in this case “are inserted in the appropriate place in the parentheses:

Repchar("-", 43); // function call specifies actual values

This statement instructs repchar ( ) to print a line of 43 dashes. The values supplied in the call must be of the types specified in the declaration: the first argument, the “-” character , must be of type[ char; and the second arguments, the number 43 must be of type int. The types in the definition must also agree.

The next call to repchar ( ).

Repchar ("=" , 23);

Tells it to print a line of 23 equal signs. The third call again prints 43 dashes. Here”s the output form tablearg.cpp.

The calling program supplies arguments such as “-” and 43 ,to the function. The variables used within the functions to hold the argument values are called parameters; in repchar() the are ch and n.These decelerator names ch and n, are used in the functions as they were normal variables. Placing them in the decelerators is equivalent to defining them with the statements like

When the function is called, its parameters are automatically initialized to the values passed by the calling program.

Passing Variables

In the tablearg.cpp example the arguments were constants (“-” 43),and so on. Lets look at an example where variables, instead of constants ,are passed as arguments. This program, incorporates the same repchar()function as did tablearg.cpp,but let the user specify the character and the number of times it should be repeated.

Here is some sample interaction with var arg

Here chin and nin in main() are used as arguments to repchar():

rephar()(chin,nin); // function call

The data types of variables used as arguments must match those specified in the function declaration and definition, just as they must for constant. That is chin must be a char and nin must be an int.

Returning Values from Functions

When a function completes its execution, it can return a single value to the calling program. Usually this return value consists of an answer to the problem the function has solved. The next example demonstrates a function that returns a weight in kg after being given a weight in ponds.

When a function returns a value. The data type of this value must be specified. The function declaration does this by placing the data types, float in this case, before the function name in the declaration and the definition. Functions in earlier program examples returned no value, so the return type was void. In the above function lbstokg() returns type float, so the declaration is

The first float specifies the return type. The float in parentheses s specifies that an argument to be passed to lbstokg() is also of type float.

Call by Value

In the preceding examples we have seen that whenever we called a function we have always passed the values of variables to the called function. Such function calls are called “calls by value” by this what it meant is that on calling a function we are passing values of variables to it. The example of call by value are shown below ;

In this method the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual argument in the calling function. The following program illustrates this:

The output of the above program would be; x = 20 y = 10 a =10 b =20

Call by Reference

In the second method the addresses of actual arguments in the calling function are copied in to formal arguments of the called function. This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them the following program illustrates this.

The output of the above program would be a = 20 b =10

Here's Must-Read List of C programming books for beginners

C Programming LanguageC Programming Language

C Programming Language, 2nd Edition

With over 600 5-star reviews on Amazon, readers agree that C Programming Language, 2nd Edition by Brian Kernighan and Dennis Ritchie is the best C Programming book for Beginners. The authors present the complete guide to ANSI standard C language programming. Written by the developers of C, this new version helps readers keep up with the finalized ANSI standard for C while showing how to take advantage of C's rich set of operators, economy of expression, improved control flow, and data structures.

21st Century C21st Century C

21st Century C: C Tips from the New School

Throw out your old ideas about C and get to know a programming language that’s substantially outgrown its origins. With this revised edition of 21st Century C, you’ll discover up-to-date techniques missing from other C tutorials, whether you’re new to the language or just getting reacquainted.

C Programming Absolute Beginner's GuideC Programming Absolute Beginner's Guide

C Programming Absolute Beginner's Guide

Greg Perry is the author of over 75 computer books and known for bringing programming topics down to the beginner’s level. His book C Programming Absolute Beginner's Guide, is today’s best beginner’s guide to writing C programs–and to learning skills to use with practically any language. Its simple, practical instructions will help you start creating useful, reliable C code, from games to mobile apps. Plus, it’s fully updated for the new C11 standard and today’s free, open source tools!

C ProgrammingC Programming

C Programming: A Modern Approach, 2nd Edition

KN King tackles on some C standard library specifics header by header in his C Programming: A Modern Approach book. The second edition maintains all the book's popular features and brings it up to date with coverage of the C99 standard. The new edition also adds a significant number of exercises and longer programming projects, and includes extensive revisions and updates.

Programming ArduinoProgramming Arduino

Programming Arduino: Getting Started with Sketches

Simon Monk, a Ph.D. in software engineering, writes this great little book for learning to program the arduino using C language. This bestselling guide explains how to write well-crafted sketches using Arduino’s modified C language. You will learn how to configure hardware and software, develop your own sketches, work with built-in and custom Arduino libraries, and explore the Internet of Things—all with no prior programming experience required!