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)

PPTX
functions
Makwana Bhavesh
 
PPTX
UNIT3.pptx
NagasaiT
 
PPT
C++ Language
Syed Zaid Irshad
 
PPTX
C and C++ functions
kavitha muneeshwaran
 
PPTX
Function (rule in programming)
Unviersity of balochistan quetta
 
PPT
eee2-day4-structures engineering college
2017eee0459
 
PPT
Functions123
sandhubuta
 
PPT
Functions12
sandhubuta
 
PDF
4th unit full
Murali Saktheeswaran
 
PPT
Part 3-functions
ankita44
 
PPT
C++ Functions.ppt
WaheedAnwar20
 
PDF
Bartosz Milewski, “Re-discovering Monads in C++”
Platonov Sergey
 
PPTX
C++11: Feel the New Language
mspline
 
PPTX
C concepts and programming examples for beginners
SHAAMILIRAJAKUMAR1
 
PPTX
unit_2 (1).pptx
JVenkateshGoud
 
PPTX
Silde of the cse fundamentals a deep analysis
Rayhan331
 
PPT
L4 functions
mondalakash2012
 
PPTX
Cs1123 8 functions
TAlha MAlik
 
PPTX
Functions in C++ (OOP)
Faizan Janjua
 
functions
Makwana Bhavesh
 
UNIT3.pptx
NagasaiT
 
C++ Language
Syed Zaid Irshad
 
C and C++ functions
kavitha muneeshwaran
 
Function (rule in programming)
Unviersity of balochistan quetta
 
eee2-day4-structures engineering college
2017eee0459
 
Functions123
sandhubuta
 
Functions12
sandhubuta
 
4th unit full
Murali Saktheeswaran
 
Part 3-functions
ankita44
 
C++ Functions.ppt
WaheedAnwar20
 
Bartosz Milewski, “Re-discovering Monads in C++”
Platonov Sergey
 
C++11: Feel the New Language
mspline
 
C concepts and programming examples for beginners
SHAAMILIRAJAKUMAR1
 
unit_2 (1).pptx
JVenkateshGoud
 
Silde of the cse fundamentals a deep analysis
Rayhan331
 
L4 functions
mondalakash2012
 
Cs1123 8 functions
TAlha MAlik
 
Functions in C++ (OOP)
Faizan Janjua
 

More from ssuserbad56d (11)

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

Recently uploaded (20)

PPTX
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
PDF
Geographical diversity of India short notes by sandeep swamy
Sandeep Swamy
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PDF
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
QUARTER 1 WEEK 2 PLOT, POV AND CONFLICTS
KynaParas
 
Geographical diversity of India short notes by sandeep swamy
Sandeep Swamy
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Dimensions of Societal Planning in Commonism
StefanMz
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
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