Functions in C

Functions:

  • A function is a self-contained unit of program code designed to accomplish a task.
  • Syntax rule define the structure of a function and how it can be used
  • A function in C is the same as subroutines or procedures in other programming language.
  • Some functions cause an action to take place
  • printf() cause data to be printed on your screen.
  • Some functions find a value for a program to use.
  • strlen():The C library function size_t strlen(const char *str)        computes the length of the string str up to, but not including     the terminating null character.
  • Advantages:
  • Allow for the divide and conquer strategy so that it will be easy to compile and debug the program.
  • It is very hard to write an entire program as a single large main function.
  • With the divide and conquer tasks can be divided into several independent subtasks reduces the complexity.
  • Separate functions are written for each subtask.
  • We can also divide each subtask into smaller subtask to reduce the complexity.
  • Reduces the duplication of code.
  • Saves your time when writing, testing, and debugging the code.
  • Reduces the size of the source code.
  • If you want to do a certain task several times in a program, you only need to write an appropriate function once
  • Program can then use that function whenever needed.
  • You can also use the same function in different programs (printf).
  •    Helps with readability.
  • Program is bitterly organized
  • Easier to reads and easier to change or fix.
  • Reduces the overall time for development.
  • The function developed for one program can be used for another program.

Example of Functions:

#define SIZE 50

int main(void)

{

float list[SIZE];

readlist(list, SIZE);

sort(list, SIZE);

average(list, SIZE);

return -;

}

  • Implementing functions:
  • Remember just calling functions does not work unless we implement the function itself
  • User defined functions
  • We would have to write the code for the three functions readlist(), sort(). and average() in our previous example.
  • Always use descriptive function name to make it clear what the program does and how it is organized.
  • If you can make the functions general, enough you can reuse them in other programs.

Main() function:

  • Indicates where the program is to begin execution.
  • All C programs must have main().
  • Can pass data to it (command line argument).
  • Returning data optional (error code).

          Defining functions:

  • When you create a function in C you need to specify the function header as the first lune of the function definition followed by curly braces.
  • The executable code is between the starting and ending of the braces.
  • The block of code between the braces following the function header is called function body.
  • Function header defines the name of the function.
  • Parameters
  • The type of value that the function returns.
  •  The function body contains the statements that are executed when the function is called
  • Have access to any values that are passed as arguments to the function.
  • Return_type Function_name (Parameters – separated by commas)
    • {
      • // Statements..
    • }
  • The first line of the function definition tells the compiler three things about the function:
  • The type of value it returns
  • It’s, name
  • The argument it takes
  • Choosing meaningful names increase the readability of the program.
  • Example:
    • void printMessage (void)
    • {
    • printf(“Programming is fun\n”);
    • }
  • The statement of a body may be absent, but the braces must be present.
  • If there are no statements in the body of a function, the return type must be void and void function will not return to anything.
  • Defining an empty body is often useful for testing the phase of a complicated program.
  • Allows you to run the program with only selected functions doing something
  • Naming the function:
  • The name of the function can be any legal name.
  • Not a reserved word (int, float, double, etc)
  • Is not as the same name as another function in your program.
  • Is not the same name as any of the standard library functions would prevent you from using the library function.
  • A legal name has the same form as that of a variable.
  • A sequence of letters and digits.
  • First character must be a letter.
  • Underline character counts as a letter.
  • The name that you choose should be meaningful and relevant to what the function does.
  • There are three common approaches you can adopt the naming of a function:
  • Separate each of the word in a function name with an underline character.
  • Capitalize the first letter of each word.
  • Capitalize words after the first. (camelCase)
  • Can pick any method but must follow the same approach throughout the code.
  • Function prototypes:
  • A function prototype is a statement that defines a function.
  • Defines the name, its return value type, and the type of each of its parameters.
  • Provides an external specification for the function.
  • You can write a prototype for a function the same as the function header.
  • Only difference is the you put a semicolon at the end.
  • Example: void printMessage (void);
  • A function prototype enables the compiler to generate the appropriate instructions at each point where you call the function.
  • It also checks that you are using the function correctly in each invocation.
  • When you include standard header file in a program, the header file adds the function prototypes for that library to your program
  • The header file stdio.h contains function prototype for printf(), among others.
  • Generally, appear at the beginning of the program.
  • Allows any functions in the file to call any function regardless of where you have placed the implementation of the functions.
  • Parameter names do not have to be the same as those used in the function definition.
  • Not required to include the names of parameters in a function prototype.
  • Example:
    • #include & define directives
    • // Function prototypes
    • double average(double data_values[], size_t count);
    • double sum(double*x, size_t n);
    • size_t GetData(double*, size_t);
  • int main(void)
    • {
      • // code in main()…

}

Example in Compiler:

#include<stdio.h>

void add()

{

}

int main()

{

  add;

  return 0;

}

Arguments and Parameters:

  • A parameter is a variable in a function declaration and function definition.
  • When a function is called, argument is the data where you pass function parameters.
  • Function parameters are defined within the function header is the placeholder for the arguments that need to be specified when the function is called
  •  The parameters for a function are a list of parameter name with their types.
  • Each parameter is separated by comma
  • Entire list of parameters is enclosed within parenthesis that follow the function name.
  • A function can have no parameters, in which case you must put void between parenthesis.
  • Parameters pass data to function.
  • The names of the parameters are local to the function
  • The body of the function must use this parameter in its implementation.
  • A function body may have additional locally defined variables that are needed by the function’s implementation.
  • When passing an array as an argument to a function
  • You must also pass an additional argument by specifying the size of an array
  •  The function has no means of knowing how many elements there in an array are.
  •  When the printf function is called, you always supply one or more values as arguments
  • First value being the format string
  • The remaining values being any variables to displayed.
  • Parameters greatly increase the usefulness and flexibility of a function.
  • The printf() function displays whatever you tell to display via the parameters and arguments passed.
  • Example:
    #include<stdio.h>

  Void multiplyTwonumbers(int x, int y)

{

  Result = x * y;

printf(“The product of %d is multiplied by %d is %d\n”, x, y, result);

}

  void main()

{

multiplyTwonumbers(10, 20);

multiplyTwonumbers(20, 40);

   getch();

}

 Returning data from functions:

  • Functions can return data using specific syntax in C.
  • Return_type Function_name(List of Pararmeters – separated by commas)

{

\\ Statement…

}

  • You can specify the type of value to be returned in C until unless they are legal in C.
  • Includes enumeration and pointers.
  • The return type can also be type void which means no value to be returned.

The return statement:

  • The return statement approves that it is the exit part of the function.
    • return 0;
  • this form of the return statement is used extensively in a function where there is no value to return.
  •  The general form of return statement is:
  •  return expression;
  • This form of return statement must be used when the return value type for the statement has been declared something other than void.
  • If we will not assign to return to a statement, then the compiler will prompt an error that the program has, not returned to a value.
  • If the expression result in a value that’s different from the return value type in the function header the compiler will insert a conversation from the type of expression to one required.
  • If we consider an example that we have an int variable datatype which have some error then the header file will convert the program into float and same with the float then the float will convert into int.
  • If at all the error isn’t ratified, then the compiler will prompt a message that there is some error.
  • We can assign multiple return values which will increase the complexity of the program.

Invoking a function:

  • You can call a function by function name followed by the arguments to the function between parenthesis.
  • When we call the function the values of the arguments that you specify in the call will be assigned to the parameters of the function.
  • When the function executes the computation proceeds using the values you supplied as arguments.
  • The arguments specified when you call a function should agree in type, number, and sequence, with the parameters in the function header.

Scroll to top