SlideShare une entreprise Scribd logo
1  sur  42
Functions
• A function is a sub program, which performs a
particular task when called.
• A C program is a collection of some functions.
• main() is the predefined function from where the
execution of a program starts.
• C program = Main() + user defined functions
..continued
• Uses of functions:
• Re-useability
• Modularity
• Re-usability: C functions are used to avoid rewriting same code again and
again in a program.
• We can call functions any number of times in a program and from any place in
a program for the same task to be performed.
• Modularity: Dividing a big task into small pieces improves understandability
of very large C programs.
• A large C program can easily be tracked when it is divided into functions.
Defining a Function
• Syntax:
function definition function
declaration
return_type function_name(List of
parameters)
{
//set of statements
function body
..continued
• Function definition – This contains all the
statements to be executed.
Function definition = function declaration +function body
A function body is a group of statements enclosed
in flower brackets.
eg: void main() function declaration
{
int a=10; function definition
function body
printf(“a = %d”,a);
}
Function terminology
• Function prototype
• Function definition
• Function call
Function prototype or declaration - This informs
compiler about the function name, function
parameters and return value’s data type.
Syntax: return_type function_name(parameter list);
This is written before main() function. To inform the
compiler that there exists a function in the program.
Function Call
• This statement actually calls the function.
• Syntax: function_name( list of parameter
values);
• This statement is written in the calling
function.
• With this statement, the control is
transferred to the function definition.
• Eg: sum(10,20);
Function calls
• Functions can be defined in any one of the
following 4 different ways.
 No arguments , No return value .
 No arguments , With return value .
 With arguments , No return value .
 With arguments , With return value .
• Arguments:-
These values are passed from main()
function to the invoked function . Generally
Ex:- Program to print the sum of given two numbers using
functions?
i)No arguments , No return value
void add ( ) ; //function
prototype
void main()
{
add(); //function calling
}
void add() //function definition
{
int a,b,c;
ii)No arguments , With return value
int add ( ) ; //function prototype
void main()
{
printf(“nsum is=%d”,add()); //
function call
}
int add() ; //function definition
{
int a,b,c;
iii)With arguments , No return value
void add ( int , int ) ; //function
prototype
void main()
{
int a , b ;
printf(“enter any two numbers”);
scanf(“%d%d”,&a,&b);
add(a,b); //function call
}
iv)With arguments , With return value
int add ( int , int ) ; //function
prototype
void main()
{
int a , b ;
printf(“enter any two numbers”);
scanf(“%d%d”,&a,&b);
printf(“sum is=%d”,add(a,b));
//function call
Methods of Function calls
There are two methods
that a C function can
be called from a
program. They are,
Call by value Call by reference
Arguments
• Actual Argument: This is the argument
which is used in the function call.
– Eg: sum(a,b); // a and b are actual arguments
• Formal Argument: This is the argument
which is used in the function definition.
– Eg: void sum(int m, int n) //m and n are
formal arguments.
{
.
.
}
Call/pass by value
• In this method, the values only values of
actual arguments are passed into formal
arguments.
• Different Memory is allocated for both
actual and formal parameters.
• The value of the actual parameter can not
be modified by formal parameter.
Call/pass by reference
– In this method, the address of the variable, not value ,is
passed to the function as parameter.
– Same memory is used for both actual and formal
parameters since only address is used by both
parameters.
– The value of the actual parameter can be modified by
formal parameter.
Recursion
• It is possible in c for functions to call
themselves.
• Recursion is a technique in which a
function calls itself.
• Eg: int fact(int a) //function definition
{
int f;
if(a==1)
return 1;
else
f=a*fact(a-1); //function call
Scope of the variable
• Two kinds of variables: Local and Global
– Local - A variable declared within the function
is called as local variable. This can be used
within that function only.
• Eg: void main()
{
int x,y;
.
.
}
X and y are local variables. Their scope is upto main function.
They can be used in only main function.
Scope of the variables
• Global variable: A variable declared global
section of the program. This can be used
anywhere in the program.
• Eg: int x; // global variable
void main()
{
int y; // local variable
.
}
void sum()
{
int a,b,c; //local variables
.
C – Storage Class Specifiers
• Storage class specifiers tells the compiler
– where to store a variable,
– how to store the variable,
– what is the initial value of the variable and
– life time of the variable.
• Syntax: storage_specifier data_type
variable _name
• Types : 4
– auto
– extern
auto
• The scope of this auto variable is within
the function only.
• It is declared using auto keyword. It is
equivalent to local variable.
• All local variables are auto variables by
default.
extern
• The scope of the extern variable is global.
• It is available throughout the main
program.
• Is declared using the keyword extern. Can
be declared anywhere in the program.
• It is stored in memory.
static
• It’s scope is local. It’s value persists
between function calls.
• Declared using static keyword.
• Stored in memory.
• Default is zero.
register
• Scope is local.
• Available within the function.
• Stored in register memory.
• Default value is garbage value.
• Declared using register keyword.
…continued
S.No
.
Storage
Specifier
Storage
place
Initial /
default
value
Scop
e
Life
1 auto
CPU
Memory
Garbage
value
local Within the function only.
2 extern
CPU
memory
Zero Global
Till the end of the main program. Variable
definition might be anywhere in the C
program
3 static
CPU
memory
Zero local
Retains the value of the variable between
different function calls.
4 register
Register
memory
Garbage
value
local Within the function
Structures
• A structure is a collection of one or more
variables, usually of different types,
grouped together under a single name.
• A structure can be declared using the
keyword ‘struct’.
• Syntax: struct structure_name
{
Structure example
• structure example: struct book
{
char book_name[20];
char author[20];
int no_of_pages;
float price;
}
Structure members
• Each variable inside the structure
definition is called a structure member.
• In the book example above,
book_name , author, no_of_pages and
price are the struct members.
Structure variables
• A structure variable can be declared using
the structure name.
• Syntax:
struct struct_name
variable_name1,variable_name2,…;
• Example: struct book b1,b2,b3;
Accessing structure members
• Structure members can be accessed using
the dot(.) operator.
• Syntax : struct_variable . struct
member;
• Example : b1.book_name;
b2.book_name;
etc.,
Initializing structure members
• Intializing can be done in two ways:
1. using assignment operator (=)..
2. from the keyboard
1. Using the assignment operator:
eg: b1.no_of_pages=100;
b1. price=235;
2. From the keyboard:
eg: scanf(“%d”,&b1.no_of_pages);
Array of structures
• An array of structures can be declared in
the same way we declare any other array.
• Example: struct book b1[10];
b1 is the array of structures which
holds 10 structures.
• Each structure variable is accessed
using the array index.
Union
• A Union is a collection of one or more
variables, usually of different types,
grouped together under a single name.
• A union can be declared using the
keyword ‘union’.
• Syntax: union union_name
{
union example
• Union example: union book
{
char book_name[20];
char author[20];
int no_of_pages;
float price;
}
Union members
• Each variable inside the union definition is
called a union member.
• In the book example above,
book_name , author, no_of_pages and
price are the union members.
union variables
• A union variable can be declared using the
union name.
• Syntax:
union union_name
variable_name1,variable_name2,…;
• Example: union book b1,b2,b3;
Accessing union members
• union members can be accessed using
the dot(.) operator.
• Syntax : union_variable .union
member;
• Example : b1.book_name;
b2.book_name;
etc.,
Initializing union members
• Intializing can be done in two ways:
1. using assignment operator (=)..
2. from the keyboard
1. Using the assignment operator:
eg: b1.no_of_pages=100;
b1. price=235;
2. From the keyboard:
eg: scanf(“%d”,&b1.no_of_pages);
Array of unions
• An array of unions can be declared in the
same way we declare any other array.
• Example: union book b1[10];
b1 is the array of unions which
holds 10 unions.
• Each union variable is accessed using
the array index.
Differences between structure and
union
S.no C Structure C Union
1 Structure allocates storage space for all its members separately.
Union allocates one common storage space for all its
members.
Union finds that which of its member needs high storage
space over other members and allocates that much space
2 Structure occupies higher memory space. Union occupies lower memory space over structure.
3 We can access all members of structure at a time. We can access only one member of union at a time.
4
Structure example:
struct student
{
int mark;
char name[6];
double average;
};
Union example:
union student
{
int mark;
char name[6];
double average;
};
5
For above structure, memory allocation will be like
below.
int mark – 2B
char name[6] – 6B
double average – 8B
Total memory allocation = 2+6+8 = 16 Bytes
For above union, only 8 bytes of memory will be allocated
since double data type will occupy maximum space of
memory over other data types.
Total memory allocation = 8 Bytes
Pointers
• A pointer is a variable which points to
another variable.
• A pointer stores the address of another
variable.
• Pointers are used to allocate memory
dynamically.
Address of operator
• & is called as ‘addressof ‘operator.
• Helps to store the address of a variable in
a pointer.
• Then the pointer points to that variable.
• A pointer variable is default initalized to
null.
Advantages of pointers
• To return more than one value from a
function.
• To pass arguments to functions by
reference.
• Pointer concepts are very useful in
development of system software.
• With the address known, data can be
accesses from any where in the
program.

Contenu connexe

Tendances

Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)Ritika Sharma
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C LanguageShaina Arora
 
Storage class in c
Storage class in cStorage class in c
Storage class in ckash95
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programmingprogramming9
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 

Tendances (20)

Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Strings in C
Strings in CStrings in C
Strings in C
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
File handling in c
File handling in cFile handling in c
File handling in c
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Function in C
Function in CFunction in C
Function in C
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 
Storage class in c
Storage class in cStorage class in c
Storage class in c
 
This pointer
This pointerThis pointer
This pointer
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Function in c
Function in cFunction in c
Function in c
 

En vedette

Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingSivant Kolhe
 
Lets tune-in-to-europe
Lets tune-in-to-europeLets tune-in-to-europe
Lets tune-in-to-europeSPKoszecin
 
Токийский гуль
Токийский гульТокийский гуль
Токийский гульDima Luk
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programminggajendra singh
 
PUCPR Aspectos Legais - Aula 2 responsabilidade civil do médico
PUCPR Aspectos Legais - Aula 2   responsabilidade civil do médicoPUCPR Aspectos Legais - Aula 2   responsabilidade civil do médico
PUCPR Aspectos Legais - Aula 2 responsabilidade civil do médicoalcindoneto
 
La rinconada18mar17m ldealfonsorodriguezvera[1]
La rinconada18mar17m ldealfonsorodriguezvera[1]La rinconada18mar17m ldealfonsorodriguezvera[1]
La rinconada18mar17m ldealfonsorodriguezvera[1]Winston1968
 
Energy sector in india 2017 basics and post budget insights arindam (1)
Energy sector in india 2017 basics and post budget insights  arindam (1)Energy sector in india 2017 basics and post budget insights  arindam (1)
Energy sector in india 2017 basics and post budget insights arindam (1)Mr. Arindam Bhattacharjee
 
Les cancers de l’endomètre : actualités 2016
Les cancers de l’endomètre : actualités 2016Les cancers de l’endomètre : actualités 2016
Les cancers de l’endomètre : actualités 2016Elisabeth RUSS
 
Behavioral Weight Loss Interventions.State of the Science, Alex Psychiatry 26...
Behavioral Weight Loss Interventions.State of the Science, Alex Psychiatry 26...Behavioral Weight Loss Interventions.State of the Science, Alex Psychiatry 26...
Behavioral Weight Loss Interventions.State of the Science, Alex Psychiatry 26...Nilly Shams
 
презентация 8 марта
презентация 8 мартапрезентация 8 марта
презентация 8 мартаvirtualtaganrog
 
Cassavabase workshop ibadan March17
Cassavabase workshop ibadan March17Cassavabase workshop ibadan March17
Cassavabase workshop ibadan March17solgenomics
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)Dushmanta Nath
 

En vedette (15)

Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Lets tune-in-to-europe
Lets tune-in-to-europeLets tune-in-to-europe
Lets tune-in-to-europe
 
Токийский гуль
Токийский гульТокийский гуль
Токийский гуль
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Ppt 1
Ppt 1Ppt 1
Ppt 1
 
PUCPR Aspectos Legais - Aula 2 responsabilidade civil do médico
PUCPR Aspectos Legais - Aula 2   responsabilidade civil do médicoPUCPR Aspectos Legais - Aula 2   responsabilidade civil do médico
PUCPR Aspectos Legais - Aula 2 responsabilidade civil do médico
 
La rinconada18mar17m ldealfonsorodriguezvera[1]
La rinconada18mar17m ldealfonsorodriguezvera[1]La rinconada18mar17m ldealfonsorodriguezvera[1]
La rinconada18mar17m ldealfonsorodriguezvera[1]
 
Energy sector in india 2017 basics and post budget insights arindam (1)
Energy sector in india 2017 basics and post budget insights  arindam (1)Energy sector in india 2017 basics and post budget insights  arindam (1)
Energy sector in india 2017 basics and post budget insights arindam (1)
 
Les cancers de l’endomètre : actualités 2016
Les cancers de l’endomètre : actualités 2016Les cancers de l’endomètre : actualités 2016
Les cancers de l’endomètre : actualités 2016
 
Behavioral Weight Loss Interventions.State of the Science, Alex Psychiatry 26...
Behavioral Weight Loss Interventions.State of the Science, Alex Psychiatry 26...Behavioral Weight Loss Interventions.State of the Science, Alex Psychiatry 26...
Behavioral Weight Loss Interventions.State of the Science, Alex Psychiatry 26...
 
презентация 8 марта
презентация 8 мартапрезентация 8 марта
презентация 8 марта
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Cassavabase workshop ibadan March17
Cassavabase workshop ibadan March17Cassavabase workshop ibadan March17
Cassavabase workshop ibadan March17
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
 

Similaire à C Functions Guide: Everything You Need to Know

Similaire à C Functions Guide: Everything You Need to Know (20)

CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Functions
FunctionsFunctions
Functions
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Function (rule in programming)
Function (rule in programming)Function (rule in programming)
Function (rule in programming)
 
C language updated
C language updatedC language updated
C language updated
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
Functions
FunctionsFunctions
Functions
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
 
FUNCTIONS IN C.pptx
FUNCTIONS IN C.pptxFUNCTIONS IN C.pptx
FUNCTIONS IN C.pptx
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
Functions
Functions Functions
Functions
 
Modular Programming in C
Modular Programming in CModular Programming in C
Modular Programming in C
 

Dernier

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Dernier (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

C Functions Guide: Everything You Need to Know

  • 1. Functions • A function is a sub program, which performs a particular task when called. • A C program is a collection of some functions. • main() is the predefined function from where the execution of a program starts. • C program = Main() + user defined functions
  • 2. ..continued • Uses of functions: • Re-useability • Modularity • Re-usability: C functions are used to avoid rewriting same code again and again in a program. • We can call functions any number of times in a program and from any place in a program for the same task to be performed. • Modularity: Dividing a big task into small pieces improves understandability of very large C programs. • A large C program can easily be tracked when it is divided into functions.
  • 3. Defining a Function • Syntax: function definition function declaration return_type function_name(List of parameters) { //set of statements function body
  • 4. ..continued • Function definition – This contains all the statements to be executed. Function definition = function declaration +function body A function body is a group of statements enclosed in flower brackets. eg: void main() function declaration { int a=10; function definition function body printf(“a = %d”,a); }
  • 5. Function terminology • Function prototype • Function definition • Function call Function prototype or declaration - This informs compiler about the function name, function parameters and return value’s data type. Syntax: return_type function_name(parameter list); This is written before main() function. To inform the compiler that there exists a function in the program.
  • 6. Function Call • This statement actually calls the function. • Syntax: function_name( list of parameter values); • This statement is written in the calling function. • With this statement, the control is transferred to the function definition. • Eg: sum(10,20);
  • 7. Function calls • Functions can be defined in any one of the following 4 different ways.  No arguments , No return value .  No arguments , With return value .  With arguments , No return value .  With arguments , With return value . • Arguments:- These values are passed from main() function to the invoked function . Generally
  • 8. Ex:- Program to print the sum of given two numbers using functions? i)No arguments , No return value void add ( ) ; //function prototype void main() { add(); //function calling } void add() //function definition { int a,b,c;
  • 9. ii)No arguments , With return value int add ( ) ; //function prototype void main() { printf(“nsum is=%d”,add()); // function call } int add() ; //function definition { int a,b,c;
  • 10. iii)With arguments , No return value void add ( int , int ) ; //function prototype void main() { int a , b ; printf(“enter any two numbers”); scanf(“%d%d”,&a,&b); add(a,b); //function call }
  • 11. iv)With arguments , With return value int add ( int , int ) ; //function prototype void main() { int a , b ; printf(“enter any two numbers”); scanf(“%d%d”,&a,&b); printf(“sum is=%d”,add(a,b)); //function call
  • 12. Methods of Function calls There are two methods that a C function can be called from a program. They are, Call by value Call by reference
  • 13. Arguments • Actual Argument: This is the argument which is used in the function call. – Eg: sum(a,b); // a and b are actual arguments • Formal Argument: This is the argument which is used in the function definition. – Eg: void sum(int m, int n) //m and n are formal arguments. { . . }
  • 14. Call/pass by value • In this method, the values only values of actual arguments are passed into formal arguments. • Different Memory is allocated for both actual and formal parameters. • The value of the actual parameter can not be modified by formal parameter.
  • 15. Call/pass by reference – In this method, the address of the variable, not value ,is passed to the function as parameter. – Same memory is used for both actual and formal parameters since only address is used by both parameters. – The value of the actual parameter can be modified by formal parameter.
  • 16. Recursion • It is possible in c for functions to call themselves. • Recursion is a technique in which a function calls itself. • Eg: int fact(int a) //function definition { int f; if(a==1) return 1; else f=a*fact(a-1); //function call
  • 17. Scope of the variable • Two kinds of variables: Local and Global – Local - A variable declared within the function is called as local variable. This can be used within that function only. • Eg: void main() { int x,y; . . } X and y are local variables. Their scope is upto main function. They can be used in only main function.
  • 18. Scope of the variables • Global variable: A variable declared global section of the program. This can be used anywhere in the program. • Eg: int x; // global variable void main() { int y; // local variable . } void sum() { int a,b,c; //local variables .
  • 19. C – Storage Class Specifiers • Storage class specifiers tells the compiler – where to store a variable, – how to store the variable, – what is the initial value of the variable and – life time of the variable. • Syntax: storage_specifier data_type variable _name • Types : 4 – auto – extern
  • 20. auto • The scope of this auto variable is within the function only. • It is declared using auto keyword. It is equivalent to local variable. • All local variables are auto variables by default.
  • 21. extern • The scope of the extern variable is global. • It is available throughout the main program. • Is declared using the keyword extern. Can be declared anywhere in the program. • It is stored in memory.
  • 22. static • It’s scope is local. It’s value persists between function calls. • Declared using static keyword. • Stored in memory. • Default is zero.
  • 23. register • Scope is local. • Available within the function. • Stored in register memory. • Default value is garbage value. • Declared using register keyword.
  • 24. …continued S.No . Storage Specifier Storage place Initial / default value Scop e Life 1 auto CPU Memory Garbage value local Within the function only. 2 extern CPU memory Zero Global Till the end of the main program. Variable definition might be anywhere in the C program 3 static CPU memory Zero local Retains the value of the variable between different function calls. 4 register Register memory Garbage value local Within the function
  • 25. Structures • A structure is a collection of one or more variables, usually of different types, grouped together under a single name. • A structure can be declared using the keyword ‘struct’. • Syntax: struct structure_name {
  • 26. Structure example • structure example: struct book { char book_name[20]; char author[20]; int no_of_pages; float price; }
  • 27. Structure members • Each variable inside the structure definition is called a structure member. • In the book example above, book_name , author, no_of_pages and price are the struct members.
  • 28. Structure variables • A structure variable can be declared using the structure name. • Syntax: struct struct_name variable_name1,variable_name2,…; • Example: struct book b1,b2,b3;
  • 29. Accessing structure members • Structure members can be accessed using the dot(.) operator. • Syntax : struct_variable . struct member; • Example : b1.book_name; b2.book_name; etc.,
  • 30. Initializing structure members • Intializing can be done in two ways: 1. using assignment operator (=).. 2. from the keyboard 1. Using the assignment operator: eg: b1.no_of_pages=100; b1. price=235; 2. From the keyboard: eg: scanf(“%d”,&b1.no_of_pages);
  • 31. Array of structures • An array of structures can be declared in the same way we declare any other array. • Example: struct book b1[10]; b1 is the array of structures which holds 10 structures. • Each structure variable is accessed using the array index.
  • 32. Union • A Union is a collection of one or more variables, usually of different types, grouped together under a single name. • A union can be declared using the keyword ‘union’. • Syntax: union union_name {
  • 33. union example • Union example: union book { char book_name[20]; char author[20]; int no_of_pages; float price; }
  • 34. Union members • Each variable inside the union definition is called a union member. • In the book example above, book_name , author, no_of_pages and price are the union members.
  • 35. union variables • A union variable can be declared using the union name. • Syntax: union union_name variable_name1,variable_name2,…; • Example: union book b1,b2,b3;
  • 36. Accessing union members • union members can be accessed using the dot(.) operator. • Syntax : union_variable .union member; • Example : b1.book_name; b2.book_name; etc.,
  • 37. Initializing union members • Intializing can be done in two ways: 1. using assignment operator (=).. 2. from the keyboard 1. Using the assignment operator: eg: b1.no_of_pages=100; b1. price=235; 2. From the keyboard: eg: scanf(“%d”,&b1.no_of_pages);
  • 38. Array of unions • An array of unions can be declared in the same way we declare any other array. • Example: union book b1[10]; b1 is the array of unions which holds 10 unions. • Each union variable is accessed using the array index.
  • 39. Differences between structure and union S.no C Structure C Union 1 Structure allocates storage space for all its members separately. Union allocates one common storage space for all its members. Union finds that which of its member needs high storage space over other members and allocates that much space 2 Structure occupies higher memory space. Union occupies lower memory space over structure. 3 We can access all members of structure at a time. We can access only one member of union at a time. 4 Structure example: struct student { int mark; char name[6]; double average; }; Union example: union student { int mark; char name[6]; double average; }; 5 For above structure, memory allocation will be like below. int mark – 2B char name[6] – 6B double average – 8B Total memory allocation = 2+6+8 = 16 Bytes For above union, only 8 bytes of memory will be allocated since double data type will occupy maximum space of memory over other data types. Total memory allocation = 8 Bytes
  • 40. Pointers • A pointer is a variable which points to another variable. • A pointer stores the address of another variable. • Pointers are used to allocate memory dynamically.
  • 41. Address of operator • & is called as ‘addressof ‘operator. • Helps to store the address of a variable in a pointer. • Then the pointer points to that variable. • A pointer variable is default initalized to null.
  • 42. Advantages of pointers • To return more than one value from a function. • To pass arguments to functions by reference. • Pointer concepts are very useful in development of system software. • With the address known, data can be accesses from any where in the program.