Functions in C

In this tutorial, you will learn about functions in C, which help organize code by breaking it into reusable blocks. Functions make programs more readable, efficient, and easy to manage. C has built-in library functions and user-defined functions. Let’s explore how functions work in C.

Contents:

  1. What is Function in C?
  2. Types of Functions in C
  3. Syntax of a Function in C
  4. Example of a Function in C
  5. Library Functions in C
  6. User-defined Functions in C
  7. Function Scope in C
  8. Function Pointers in C
  9. Inline Functions in C
  10. Predefined (Library) Functions in C
  11. Advantages of Functions in C
  12. FAQs on Functions in C

What is Function in C?

A function in C is a block of code that performs a specific task and can be reused throughout the program. Functions help in modular programming, making code more readable, reusable, and easier to debug.

Types of Functions in C

In C programming, functions can be categorized into two main types:

  • Library Functions – Predefined functions in C, such as printf(), scanf(), strlen(), sqrt(), etc.
  • User-defined Functions – Functions created by the programmer to perform specific tasks.

advertisement

Syntax of a Function in C

return_type function_name(parameters)
{
    // Function body
    return value;  // Optional return statement
}
  • return_type → Specifies the type of value the function returns. Use void if no value is returned.
  • function_name → The name of the function.
  • parameters → Input values (optional).
  • function body → Contains the logic of the function.
  • return → Returns a value if needed.

Example of a Function in C

#include <stdio.h>
 
// Function to print a quiz question
void sanfoundryQuiz() {
    printf("Which keyword is used to declare a function in C?\n");
    printf("A) define\nB) function\nC) void\nD) declare\n");
}
 
int main() {
    sanfoundryQuiz();  // Function call
    return 0;
}

Output:

Free 30-Day Java Certification Bootcamp is Live. Join Now!
Which keyword is used to declare a function in C?
A) define
B) function
C) void
D) declare

This C program prints a quiz question using a function. It defines sanfoundryQuiz(), which displays a multiple-choice question when called. The main() function calls this quiz function, keeping the code clean and reusable. The program ends with return 0; to indicate successful execution.

Library Functions in C

Library functions in C are built-in functions provided by the C standard library. These functions help perform common tasks like mathematical operations, input/output handling, string manipulation, and more.

Syntax:

return_type function_name(arguments);

Example 1: (Using printf and sqrt Library Functions)

#include <stdio.h>
#include <math.h>  // Library for mathematical functions
 
int main() {
    int score = 64;
 
    // Using printf (stdio.h) for output
    printf("Sanfoundry Quiz Score: %d\n", score);
 
    // Using sqrt (math.h) to find square root
    printf("Square Root of Score: %.2f\n", sqrt(score));
 
    return 0;
}

Output:

Sanfoundry Quiz Score: 64
Square Root of Score: 8.00

This C program prints a quiz score and finds its square root. It first sets score to 64 and displays it using printf() from stdio.h. Then, it uses sqrt() from math.h to calculate the square root and prints the result. Finally, the program ends successfully with return 0.

advertisement

Example 2: String Manipulation using strlen and strcat (String.h)

#include <stdio.h>
#include <string.h>  
 
int main() {
    char quiz1[] = "Sanfoundry ";
    char quiz2[] = "Quiz";
 
    // Using strlen() to find length of string
    printf("Length of first string: %lu\n", strlen(quiz1));
 
    // Using strcat() to concatenate strings
    strcat(quiz1, quiz2);
    printf("Combined String: %s\n", quiz1);
 
    return 0;
}

Output:

Length of first string: 10  
Combined String: Sanfoundry Quiz

This C program works with strings using functions from string.h. It first defines two strings, quiz1 and quiz2. The strlen() function finds the length of quiz1, which is then printed. Next, strcat() joins quiz2 to quiz1, creating a combined string. Finally, the result is displayed before the program ends.

Example 3: Mathematical Computations using pow and abs (Math.h)

#include <stdio.h>
#include <math.h>
 
int main() {
    int x = -10;
    double y = 3.0;
 
    // Using abs() to get absolute value
    printf("Absolute value of %d: %d\n", x, abs(x));
 
    // Using pow() to calculate power
    printf("2 raised to power %.1f: %.2f\n", y, pow(2, y));
 
    return 0;
}

Output:

Absolute value of -10: 10  
2 raised to power 3.0: 8.00

This C program demonstrates mathematical functions from math.h. It first declares an integer x and a double y. The abs() function calculates the absolute value of x, which is printed. Then, the pow() function raises 2 to the power of y, and the result is displayed. The program then ends.

Example 4: Character Handling using toupper and tolower (Ctype.h)

#include <stdio.h>
#include <ctype.h>
 
int main() {
    char ch1 = 's';
    char ch2 = 'Q';
 
    // Convert to uppercase
    printf("Uppercase of %c: %c\n", ch1, toupper(ch1));
 
    // Convert to lowercase
    printf("Lowercase of %c: %c\n", ch2, tolower(ch2));
 
    return 0;
}

Output:

Uppercase of s: S  
Lowercase of Q: q

This C program demonstrates character case conversion using ctype.h. It defines two characters, ch1 and ch2. The toupper() function converts ch1 to uppercase, and the tolower() function converts ch2 to lowercase. The results are printed, and the program then ends.

Example 5: Random Number Generation using rand() (stdlib.h)

#include <stdio.h>
#include <stdlib.h>
 
int main() {
    // Generate and print a random number
    printf("Sanfoundry Quiz Random Number: %d\n", rand() % 100);
 
    return 0;
}

Output (varies):

Sanfoundry Quiz Random Number: 57

This C program generates a random number using rand() from stdlib.h. The result is limited to a range of 0-99 using the modulus operator (% 100). The program then prints the random number and exits.

User-defined Functions in C

A user-defined function in C is a function created by the programmer to perform a specific task. It helps in modularizing code, improving reusability, and making the program more readable. User-defined functions in C can be categorized based on parameters and return values. The four main types are:

1. Function with No Parameters and No Return Value

A function that does not take any input and does not return any value.

Example:

#include <stdio.h>
 
// Function with no parameters and no return value
void greet() {
    printf("Hello, Sanfoundry Learners!\n");
}
 
int main() {
    greet(); // Function call
    return 0;
}

Output:

Hello, Sanfoundry Learners!

2. Function with Parameters but No Return Value

A function that accepts arguments but does not return a value.

Example:

#include <stdio.h>
 
// Function with parameters but no return value
void displayNumber(int num) {
    printf("The number is: %d\n", num);
}
 
int main() {
    displayNumber(10); // Function call with an argument
    return 0;
}

Output:

The number is: 10

3. Function with No Parameters but Returns a Value

A function that does not take arguments but returns a value.

Example:

#include <stdio.h>
 
// Function with no parameters but returns a value
int getNumber() {
    return 25;
}
 
int main() {
    int value = getNumber(); // Storing returned value
    printf("Returned number: %d\n", value);
    return 0;
}

Output:

Returned number: 25

4. Function with Parameters and Returns a Value

A function that accepts arguments and returns a value.

Example:

#include <stdio.h>
 
// Function with parameters and return value
int addNumbers(int a, int b) {
    return a + b;
}
 
int main() {
    int sum = addNumbers(8, 12); // Passing arguments
    printf("Sum: %d\n", sum);
    return 0;
}

Output:

Sum: 20

Function Scope in C

Function scope determines where a function or variable can be accessed in the program. The major types of scope in C are:

1. Local Scope

Variables declared inside a function are local to that function. They cannot be accessed outside the function.

Example:

#include <stdio.h>
 
void display() {
    int x = 10; // Local variable
    printf("Value of x inside function: %d\n", x);
}
 
int main() {
    display();
    // printf("%d", x); // Error! x is not accessible here.
    return 0;
}

Output:

Value of x inside function: 10

2. Global Scope

A global variable is declared outside all functions. It can be accessed anywhere in the program.

Example:

#include <stdio.h>
 
int globalVar = 100; // Global variable
 
void display() {
    printf("Global Variable: %d\n", globalVar);
}
 
int main() {
    display();
    printf("Accessing globalVar in main(): %d\n", globalVar);
    return 0;
}

Output:

Global Variable: 100
Accessing globalVar in main(): 100

3. Block Scope

Variables declared inside a block {} are only accessible within that block.

Example:

#include <stdio.h>
 
int main() {
    int x = 5;
    {
        int y = 10; // Block-scoped variable
        printf("Inside block: x = %d, y = %d\n", x, y);
    }
    // printf("%d", y); // Error! y is not accessible here.
    return 0;
}

Output:

Inside block: x = 5, y = 10

4. Function Scope

A function name itself has a global scope, meaning it can be called anywhere in the program.

Example:

#include <stdio.h>
 
// Function with global scope
void sayHello() {
    printf("Hello, Sanfoundry Learners!\n");
}
 
int main() {
    sayHello(); // Can be called anywhere
    return 0;
}

Output:

Hello, Sanfoundry Learners!

Function Pointers in C

A function pointer is a pointer that stores the address of a function. It allows functions to be called dynamically at runtime.

Syntax:

return_type (*pointer_name)(parameter_list);

Example of Function Pointer

#include <stdio.h>
 
// Function to be pointed
void greet() {
    printf("Hello, Sanfoundry Learners!\n");
}
 
int main() {
    // Declare a function pointer
    void (*ptr)();
 
    // Assign address of function
    ptr = &greet;
 
    // Call function using function pointer
    (*ptr)();
 
    return 0;
}

Output:

Hello, Sanfoundry Learners!

This C program demonstrates function pointers. The greet() function prints a message. A function pointer ptr is declared and assigned the address of greet. The function is then called using (*ptr)(), showing how pointers can be used to invoke functions dynamically.

Inline Functions in C

An inline function is a function that is expanded at the point of its call, instead of executing a separate function call. It is used to reduce function call overhead and improve program execution speed.

Syntax:

inline return_type function_name(parameters) {
    // Function body
}

Example of an Inline Function

#include <stdio.h>
 
// Define an inline function
inline int square(int x) {
    return x * x;
}
 
int main() {
    int num = 5;
    printf("Square of %d is %d\n", num, square(num));
    return 0;
}

Output:

Square of 5 is 25

This C program demonstrates an inline function. The square() function computes the square of a number. Since it’s defined as inline, the compiler may replace function calls with the actual computation, improving performance. The program calculates and prints the square of num using this function.

Predefined (Library) Functions in C

Here’s a list of predefined (library) functions in C along with their descriptions:

Function Description
printf() Prints formatted output to the console.
scanf() Reads formatted input from the user.
puts() Outputs a string followed by a newline.
fgets() Reads a line from input safely.
putchar() Prints a single character.
getchar() Reads a single character from input.
strcpy() Copies one string to another.
strcat() Concatenates two strings.
strcmp() Compares two strings lexicographically.
strlen() Returns the length of a string.
pow() Computes the power of a number.
sqrt() Returns the square root of a number.
abs() Returns the absolute value of an integer.
rand() Generates a random number.
malloc() Allocates memory dynamically.

Advantages of Functions in C

  • Code Reusability – Write once, use many times. This saves effort and avoids repeating the same code.
  • Better Readability & Maintainability – Functions break code into small parts. This makes it simple to understand and update.
  • Smaller Code Size – No need to copy the same code. Functions make programs shorter and faster.
  • Easier Debugging & Testing – You can test each function separately. This makes debugging simple.
  • Keeps Code Organized – Big programs are split into small, clear sections. This helps in managing code better.
  • Hides Complex Details – Functions keep inner details hidden. This makes programs safer and easier to use.

FAQs on Functions in C

1. What is a function in C?
A function in C is a block of code that performs a specific task and can be called multiple times within a program.

2. What are the types of functions in C?

  • Library functions (e.g., printf(), scanf())
  • User-defined functions (functions created by the programmer)

3. What is a recursive function?
A function that calls itself is called a recursive function (e.g., factorial calculation).

4. What is a function pointer in C?
A function pointer stores the address of a function and allows dynamic function calls.

5. What is an inline function?
An inline function suggests the compiler replace the function call with its code to improve speed.

6. Can a function return multiple values in C?
No, a function in C can return only one value. However, multiple values can be returned using pointers or structures.

7. What are storage classes in functions?
Storage classes (auto, static, extern, register) determine function scope and lifetime.

Key Points to Remember

Here is the list of key points we need to remember about “Functions in C”.

  • Functions allow writing code once and using it multiple times, improving efficiency.
  • C has built-in library functions like printf(), sqrt(), and user-defined functions for specific tasks.
  • A function consists of a return type, name, parameters (optional), and a body, with an optional return value.
  • Function scope determines accessibility and includes local, global, block, and function scope.
  • Function pointers store addresses of functions, enabling dynamic function calls at runtime.
  • Inline functions replace function calls with actual code to reduce execution overhead.
  • Predefined functions handle input/output, math, string manipulation, and memory allocation.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.