Cprog Functions
Cprog Functions
performs a specific task and optionally returns a value to the calling program
or/and receives values(s) from the calling program.
// calculate volume
fCubeVolume = fCubeSide * fCubeSide * fCubeSide;
// return the result to caller
return fCubeVolume;
}
C
FUNCTIONS
First line of a function definition is called the function
header, should be identical to the function prototype,
except the semicolon.
Although the argument variable names (fCubeSide in this
case) were optional in the prototype, they must be included
in the function header.
Function body, containing the statements, which the
function will perform, should begin with an opening brace
and end with a closing brace.
If the function returns data type is anything other than void
(nothing to be returned), a return statement should be
included, returning a value matching the return data type
(int in this case).
C
FUNCTIONS
The Function header
The first line of every function definition is called function header. It has 3
components, as shown below,
1. Function return type - Specifies the data type that the function should
returns to the caller program. Can be any of C data types: char, float,
int, long, double, pointers etc. If there is no return value, specify a
return type of void. For example,
/* function prototype
FUNCTIONS
*/ But it is OK if we directly declare and define the function
int funct1(int); before main() as shown below.
#include …
int main()
{ /* declare and define */
/* function call int funct1(int x)
*/ {
int y = …
funct1(3); }
…
} int main()
{
/* Function /* function call */
definition */ int y = funct1(3);
int funct1(int x) …
{…} }
Program example:
user defined
function
C
FUNCTIONS
Passing an array to a function What are the output and
#include <stdio.h> the content of num &
// function prototype
mood variables after
void Wish(int, char[ ]); program execution was
void main(void) completed?
{
Wish(5, "Happy");
}
C
#include <stdio.h>
FUNCTIONS
void Rusted(char[ ]);
Build this program, show
the output & what it do?
void main(void)
{
// all work done in function Rusted()...
Rusted("Test Test");
printf("\n");
}
void Rusted(char x[ ])
{
int j;
printf("Enter an integer: ");
scanf_s("%d", &j);
for(; j != 0; --j)
printf("In Rusted(), x = %s\n", x);
}
The identifier functptr is now a synonym for the type of 'a pointer to a
function which takes no arguments and returning int type'.
Then declaring pointers such as pTestVar as shown below, considerably
simpler,
functptr pTestVar;