SlideShare a Scribd company logo
Functions in C
Introduction to Functions
• Building blocks of modular programming
• Break complex problems into smaller, manageable pieces
• Promote code reuse and maintainability
Function Syntax
• Basic structure of a C function:
return_type function_name(parameter_list) {
// function body
return value;
}
Function Declaration vs Definition
• Declaration (prototype)
• Definition
int add(int x, int y);
int add(int x, int y) {
return x + y;
}
Function Parameters
• Parameters are variables used to pass data to functions
• Pass by value:
void modify(int x) {
x = x + 1; // Only modifies local copy
}
int main() {
int a = 5;
modify(a); // a remains 5
return 0;
}
Pass by Reference
• Using pointers to modify original values:
void modify(int *x) {
*x = *x + 1; // Modifies original value
}
int main() {
int a = 5;
modify(&a); // a becomes 6
return 0;
}
Global Variables
• Declared outside all functions
• Accessible throughout the program
int globalVar = 10; // Global variable
void function1() {
globalVar++; // Can access and modify
}
void function2() {
printf("%d", globalVar); // Can read
}
Local Variables
• Declared inside functions
• Scope limited to the containing block
void function() {
int localVar = 5; // Local variable
{
int blockVar = 10; // Block scope
}
// blockVar not accessible here
}
// localVar not accessible here
Static Local Variables
• Retain value between function calls
void counter() {
static int count = 0; // Initialized only once
count++;
printf("%dn", count);
}
Variable Scope Rules
• Scope hierarchy example
int global = 10;
void function() {
int local = 20;
{
int local = 30; // Hides outer local
printf("%dn", local); // Prints 30
}
printf("%dn", local); // Prints 20
}
Stack Frames
• Memory organization for function calls
• Each function call creates a new stack frame
• Contains:
• Local variables
• Parameters
• Return address
• Saved registers
void function(int x) {
int y = x + 1;
// Stack frame contains:
// - Parameter x
// - Local variable y
// - Return address
}
Function Call Stack
• Example of multiple function calls:
void function3() {
int z = 3;
}
void function2() {
int y = 2;
function3();
}
void function1() {
int x = 1;
function2();
}
Recursive Function Call
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
// Each recursive call creates a new stack frame
Memory Layout
• Program memory organization:
• Text segment (code)
• Data segment (global variables)
• Stack (function calls)
• Heap (dynamic allocation)
Stack Overflow
• Example of dangerous recursion:
void infinite_recursion() {
int large_array[1000]; // Local array
infinite_recursion(); // Will cause stack overflow
}
Return Values
• Common return types: void, int, float, char, etc.
• Different ways to return data:
• Simple type
• Complex type: pointers
• Struct type
int return_value() {
return 42;
}
void return_pointer(int* result) {
*result = 42;
}
struct Point return_struct() {
struct Point p = {1, 2};
return p;
}
Function Pointers
• Store address of functions, can be used to call such functions
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int main() {
int (*operation)(int, int);
operation = add;
printf("%dn", operation(5, 3)); // Prints 8
operation = subtract;
printf("%dn", operation(5, 3)); // Prints 2
return 0;
}
Function Pointers
• Function pointers can be used as parameters:
int apply(int (*func)(int), int value) {
return func(value);
}
int square(int x) {
return x * x;
}
// Usage:
int result = apply(square, 5); // Returns 25
Functions with varied parameter list
#include <stdarg.h>
int sum(int count, ...) {
va_list args;
va_start(args, count);
int total = 0;
for (int i = 0; i < count; i++) {
total += va_arg(args, int);
}
va_end(args);
return total;
}
Inline Functions
• Optimization hint to compiler:
inline int max(int a, int b) {
return (a > b) ? a : b;
}
Recursion
• Function calling itself:
int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n-1) + fibonacci(n-2);
}
int factorial_tail(int n, int accumulator) {
if (n <= 1) return accumulator;
return factorial_tail(n - 1, n * accumulator);
}
Function Overloading
• C doesn't support overloading. Functions cannot have the same name
• Alternative approaches:
int add_int(int a, int b) {
return a + b;
}
float add_float(float a, float b) {
return a + b;
}
Function Documentation
• Using comments effectively:
• @brief Calculates the sum of two integers
• @param a First integer
• @param b Second integer
• @return Sum of a and b
/**
* @brief Calculates the sum of two integers
* @param a First integer
* @param b Second integer
* @return Sum of a and b
*/
int add(int a, int b) {
return a + b;
}
Error Handling
• Return codes and error checking:
int divide(int numerator, int denominator, int* result) {
if (denominator == 0) {
return -1; // Error code
}
*result = numerator / denominator;
return 0; // Success
}
Function Composition
• Combining multiple functions:
int process_data(int data) {
data = validate(data);
data = transform(data);
data = format(data);
return data;
}
Callback Functions
• Functions as parameters:
void process_array(int arr[], int size, void (*callback)(int)) {
for (int i = 0; i < size; i++) {
callback(arr[i]);
}
}
void print_item(int x) {
printf("%dn", x);
}
Header Files
• Function declarations in headers:
// math_functions.h
#ifndef MATH_FUNCTIONS_H
#define MATH_FUNCTIONS_H
int add(int a, int b);
int subtract(int a, int b);
#endif
Best Practices
• Function design guidelines:
• Single responsibility principle
• Clear naming conventions
• Consistent parameter ordering
• Proper error handling
• Documentation
• Parameter validation
• Resource cleanup
Summary
• Functions are fundamental to C programming
• Understanding scope and lifetime is crucial
• Stack frame management affects program behavior
• Proper function design leads to maintainable code

More Related Content

Similar to Introduction to functions in C programming language (20)

Functions in C.pptx
Functions in C.pptx
Ashwini Raut
 
Functions
Functions
PralhadKhanal1
 
cp Module4(1)
cp Module4(1)
Amarjith C K
 
eee2-day4-structures engineering college
eee2-day4-structures engineering college
2017eee0459
 
unit_2.pptx
unit_2.pptx
Venkatesh Goud
 
luckfuckfunctioneekefkfejewnfiwnfnenf.pptx
luckfuckfunctioneekefkfejewnfiwnfnenf.pptx
TriggeredZulkar
 
User defined functions
User defined functions
Rokonuzzaman Rony
 
Principals of Programming in CModule -5.pdfModule-3.pdf
Principals of Programming in CModule -5.pdfModule-3.pdf
anilcsbs
 
functionsinc-130108032745-phpapp01.pdf
functionsinc-130108032745-phpapp01.pdf
mounikanarra3
 
4th unit full
4th unit full
Murali Saktheeswaran
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
Detailed concept of function in c programming
Detailed concept of function in c programming
anjanasharma77573
 
Presentation on function
Presentation on function
Abu Zaman
 
Function
Function
jayesh30sikchi
 
functions
functions
Makwana Bhavesh
 
Presentation on Function in C Programming
Presentation on Function in C Programming
Shuvongkor Barman
 
Functions-in-C-Languageby naginderdeep (1).pptx
Functions-in-C-Languageby naginderdeep (1).pptx
naginderdeepsingh4
 
Functions
Functions
Pragnavi Erva
 
C language
C language
Robo India
 
Unit-III.pptx
Unit-III.pptx
Mehul Desai
 
Functions in C.pptx
Functions in C.pptx
Ashwini Raut
 
eee2-day4-structures engineering college
eee2-day4-structures engineering college
2017eee0459
 
luckfuckfunctioneekefkfejewnfiwnfnenf.pptx
luckfuckfunctioneekefkfejewnfiwnfnenf.pptx
TriggeredZulkar
 
Principals of Programming in CModule -5.pdfModule-3.pdf
Principals of Programming in CModule -5.pdfModule-3.pdf
anilcsbs
 
functionsinc-130108032745-phpapp01.pdf
functionsinc-130108032745-phpapp01.pdf
mounikanarra3
 
Detailed concept of function in c programming
Detailed concept of function in c programming
anjanasharma77573
 
Presentation on function
Presentation on function
Abu Zaman
 
Presentation on Function in C Programming
Presentation on Function in C Programming
Shuvongkor Barman
 
Functions-in-C-Languageby naginderdeep (1).pptx
Functions-in-C-Languageby naginderdeep (1).pptx
naginderdeepsingh4
 

More from ssuserbad56d (11)

Dictionaries in Python programming language
Dictionaries in Python programming language
ssuserbad56d
 
OOP in Python Programming: Classes and Objects
OOP in Python Programming: Classes and Objects
ssuserbad56d
 
Software Testing and JUnit and Best Practices
Software Testing and JUnit and Best Practices
ssuserbad56d
 
search
search
ssuserbad56d
 
search
search
ssuserbad56d
 
Scaling Web Applications with Cassandra Presentation.ppt
Scaling Web Applications with Cassandra Presentation.ppt
ssuserbad56d
 
Cassandra
Cassandra
ssuserbad56d
 
Redis
Redis
ssuserbad56d
 
Covered Call
Covered Call
ssuserbad56d
 
Lec04.pdf
Lec04.pdf
ssuserbad56d
 
Project.pdf
Project.pdf
ssuserbad56d
 
Dictionaries in Python programming language
Dictionaries in Python programming language
ssuserbad56d
 
OOP in Python Programming: Classes and Objects
OOP in Python Programming: Classes and Objects
ssuserbad56d
 
Software Testing and JUnit and Best Practices
Software Testing and JUnit and Best Practices
ssuserbad56d
 
Scaling Web Applications with Cassandra Presentation.ppt
Scaling Web Applications with Cassandra Presentation.ppt
ssuserbad56d
 
Ad

Recently uploaded (20)

MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Himalayan Group of Professional Institutions (HGPI)
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Ad

Introduction to functions in C programming language

  • 2. Introduction to Functions • Building blocks of modular programming • Break complex problems into smaller, manageable pieces • Promote code reuse and maintainability
  • 3. Function Syntax • Basic structure of a C function: return_type function_name(parameter_list) { // function body return value; }
  • 4. Function Declaration vs Definition • Declaration (prototype) • Definition int add(int x, int y); int add(int x, int y) { return x + y; }
  • 5. Function Parameters • Parameters are variables used to pass data to functions • Pass by value: void modify(int x) { x = x + 1; // Only modifies local copy } int main() { int a = 5; modify(a); // a remains 5 return 0; }
  • 6. Pass by Reference • Using pointers to modify original values: void modify(int *x) { *x = *x + 1; // Modifies original value } int main() { int a = 5; modify(&a); // a becomes 6 return 0; }
  • 7. Global Variables • Declared outside all functions • Accessible throughout the program int globalVar = 10; // Global variable void function1() { globalVar++; // Can access and modify } void function2() { printf("%d", globalVar); // Can read }
  • 8. Local Variables • Declared inside functions • Scope limited to the containing block void function() { int localVar = 5; // Local variable { int blockVar = 10; // Block scope } // blockVar not accessible here } // localVar not accessible here
  • 9. Static Local Variables • Retain value between function calls void counter() { static int count = 0; // Initialized only once count++; printf("%dn", count); }
  • 10. Variable Scope Rules • Scope hierarchy example int global = 10; void function() { int local = 20; { int local = 30; // Hides outer local printf("%dn", local); // Prints 30 } printf("%dn", local); // Prints 20 }
  • 11. Stack Frames • Memory organization for function calls • Each function call creates a new stack frame • Contains: • Local variables • Parameters • Return address • Saved registers void function(int x) { int y = x + 1; // Stack frame contains: // - Parameter x // - Local variable y // - Return address }
  • 12. Function Call Stack • Example of multiple function calls: void function3() { int z = 3; } void function2() { int y = 2; function3(); } void function1() { int x = 1; function2(); }
  • 13. Recursive Function Call int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); } // Each recursive call creates a new stack frame
  • 14. Memory Layout • Program memory organization: • Text segment (code) • Data segment (global variables) • Stack (function calls) • Heap (dynamic allocation)
  • 15. Stack Overflow • Example of dangerous recursion: void infinite_recursion() { int large_array[1000]; // Local array infinite_recursion(); // Will cause stack overflow }
  • 16. Return Values • Common return types: void, int, float, char, etc. • Different ways to return data: • Simple type • Complex type: pointers • Struct type int return_value() { return 42; } void return_pointer(int* result) { *result = 42; } struct Point return_struct() { struct Point p = {1, 2}; return p; }
  • 17. Function Pointers • Store address of functions, can be used to call such functions int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int main() { int (*operation)(int, int); operation = add; printf("%dn", operation(5, 3)); // Prints 8 operation = subtract; printf("%dn", operation(5, 3)); // Prints 2 return 0; }
  • 18. Function Pointers • Function pointers can be used as parameters: int apply(int (*func)(int), int value) { return func(value); } int square(int x) { return x * x; } // Usage: int result = apply(square, 5); // Returns 25
  • 19. Functions with varied parameter list #include <stdarg.h> int sum(int count, ...) { va_list args; va_start(args, count); int total = 0; for (int i = 0; i < count; i++) { total += va_arg(args, int); } va_end(args); return total; }
  • 20. Inline Functions • Optimization hint to compiler: inline int max(int a, int b) { return (a > b) ? a : b; }
  • 21. Recursion • Function calling itself: int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n-1) + fibonacci(n-2); } int factorial_tail(int n, int accumulator) { if (n <= 1) return accumulator; return factorial_tail(n - 1, n * accumulator); }
  • 22. Function Overloading • C doesn't support overloading. Functions cannot have the same name • Alternative approaches: int add_int(int a, int b) { return a + b; } float add_float(float a, float b) { return a + b; }
  • 23. Function Documentation • Using comments effectively: • @brief Calculates the sum of two integers • @param a First integer • @param b Second integer • @return Sum of a and b /** * @brief Calculates the sum of two integers * @param a First integer * @param b Second integer * @return Sum of a and b */ int add(int a, int b) { return a + b; }
  • 24. Error Handling • Return codes and error checking: int divide(int numerator, int denominator, int* result) { if (denominator == 0) { return -1; // Error code } *result = numerator / denominator; return 0; // Success }
  • 25. Function Composition • Combining multiple functions: int process_data(int data) { data = validate(data); data = transform(data); data = format(data); return data; }
  • 26. Callback Functions • Functions as parameters: void process_array(int arr[], int size, void (*callback)(int)) { for (int i = 0; i < size; i++) { callback(arr[i]); } } void print_item(int x) { printf("%dn", x); }
  • 27. Header Files • Function declarations in headers: // math_functions.h #ifndef MATH_FUNCTIONS_H #define MATH_FUNCTIONS_H int add(int a, int b); int subtract(int a, int b); #endif
  • 28. Best Practices • Function design guidelines: • Single responsibility principle • Clear naming conventions • Consistent parameter ordering • Proper error handling • Documentation • Parameter validation • Resource cleanup
  • 29. Summary • Functions are fundamental to C programming • Understanding scope and lifetime is crucial • Stack frame management affects program behavior • Proper function design leads to maintainable code