Module 4: Chapter 6 - functions

The General Form of a Function

Definition

A function is a small program or program segment that performs a specific, well-defined task. Functions help divide a large program into smaller, manageable parts.

Purpose of Functions

General Form (Syntax)

ret-type function-name(parameter list)
{
  /* body of the function */
}

Explanation

Parameter Declaration Rules

Example

f(int i, int k, int j);  /* correct */
f(int i, k, float j);   /* wrong */

Function Call Flow

Types of Functions

1. Library Functions (Pre-Defined / Built-in)

Library functions are predefined functions provided by the C compiler. They perform common and standard operations and are written by the designers of the C language.

Key Points

Examples

2. User-Defined (Programmer Defined) Functions

User-defined functions are functions written by the programmer to perform specific tasks based on program requirements.

Key Points

Example

2.1 User-Defined Functions

Definition

User-defined functions are functions created by the programmer to perform specific and well-defined tasks in a program. They help divide a large program into smaller, reusable, and manageable parts.

Why Use User-Defined Functions?

Types of User-Defined Functions

Based on whether a function accepts arguments and/or returns a value, user-defined functions are classified into four types:

there are 4 types of User-Defined Functions

  1. No arguments, no return value: The function neither takes input nor returns any result.
  2. Arguments, no return value: The function takes input but does not return anything.
  3. No arguments, return value: The function does not take input but returns a result.
  4. Arguments and return value: The function takes input and returns a result.

1. No Arguments, No Return Value

This type of function neither accepts input from the calling function nor returns any value. It performs a task independently.

void display(void)
{
  printf("Hello World");
}

2. Arguments, No Return Value

This type of function accepts input through arguments but does not return any value to the calling function.

void printSum(int a, int b)
{
  printf("Sum = %d", a + b);
}

3. No Arguments, Return Value

This type of function does not accept any arguments but returns a value after performing a computation.

int getNumber(void)
{
  return 10;
}

4. Arguments and Return Value

This type of function accepts input through arguments and returns a computed result to the calling function.

int add(int x, int y)
{
  return x + y;
}

Key Points

Understanding the Scope of a Function

Definition

Scope defines where a piece of code or data can be accessed in a program. In C, a function creates its own scope, known as function (block) scope.

Function Scope

Local Variables

Function Parameters

Example: Function with Arguments

/* Returns 1 if c is found in string s, otherwise 0 */
int is_in(char *s, char c)
{
  while (*s)
    if (*s == c) return 1;
    else s++;
  return 0;
}

Explanation

Additional Notes

argc and argv — Arguments to main()

Definition

Command line arguments allow you to pass information to a program when it is executed. In C, these arguments are received by the main() function using two parameters: argc and argv.

Syntax

int main(int argc, char *argv[])
{
  /* program code */
}

Meaning of argc and argv

Important Points

Simple Example

Program that prints your name:

int main(int argc, char *argv[])
{
  if (argc != 2) {
    printf("You forgot to type your name");
    return 1;
  }
  printf("Hello %s", argv[1]);
  return 0;
}

How to Run

Argument Separation Rules

Accessing Characters in Arguments

Uses of Command Line Arguments

Additional Notes

The return Statement

Purpose of return

Key Points

Syntax

return; // no value returned (used in void functions)
return value; // returns a value

Example

int sum(int a, int b) {
  return a + b; // returns result
}

void show() {
  printf("Hello");
  return; // optional here
}

What Does main() Return?

Understanding return type of main()

Syntax

int main() {
  /* code */
  return 0; // success
}

Example

int main() {
  printf("Program executed successfully");
  return 0;
}

Return meaning

Recursion

What is Recursion?

Syntax

return-type function_name(parameter) {
  if(base_condition)
    return value; // stopping condition

  return function_name(modified_parameter); // recursive call
}

Example - Factorial using Recursion

int fact(int n) {
  if(n == 1) return 1; // base case
  return n * fact(n-1); // recursive call
}

How recursion works?

Advantages

Disadvantages

Function Prototypes

Definition

A function prototype declares a function's return type and parameter types before its use. Prototypes enable the compiler to perform strong type checking on function calls (number and types of arguments).

Why Use Prototypes?

General Syntax

return_type func_name(type param1, type param2, ..., type paramN);

Notes on Syntax

Example: Prototype that Catches a Type Error

/* Prototype enforces the argument must be int * */
void sqr_it(int *i); /* prototype */
int main(void) {
  int x = 10;
  sqr_it(x); /* compiler error: expects int * */
  return 0;
}
void sqr_it(int *i) {
  *i = *i * *i;
}

Example: Definition Used as Prototype

#include <stdio.h>
/* If defined before use, this serves as the prototype */
void f(int a, int b) {
  printf("%d ", a % b);
}
int main(void) {
  f(10, 3);
  return 0;
}

Best Practices

Summary

Declaring Variable Length Parameter Lists

In C, you can declare functions that accept a variable number of arguments. A common example is the printf() function. To specify a variable argument list, the function declaration ends with three periods ..., known as an ellipsis.

Prototype Format

At least one fixed parameter must be present. The ellipsis indicates additional optional arguments.

int func(int a, int b, ...);

Invalid Declaration Example

A function cannot have only ellipsis without fixed parameters:

int func(...); /* X illegal */

Variable-length parameter lists are powerful when argument count may differ, but require careful handling using macros like va_list, va_start, and va_arg from <stdarg.h>.

The inline Keyword

In C99, the keyword inline can be used with function declarations to suggest that the compiler should optimize the function by expanding its code directly at the call site rather than performing a usual function call. This can reduce overhead and improve execution speed, especially for small functions.

How it Works

inline int square(int x) { return x * x; }

The use of inline is beneficial when performance is critical, but it is ultimately a suggestion, not a command—compilers may or may not expand the function inline.