Basic function designs
Functions are classified by their return values and their parameters list. Functions either return a value or they don’t . Functions that don’t return a value are called void functions. Combining return types and parameters list results in the following designs:
Void functions without parameters
Void functions with parameters
Non-void functions without parameters
No-void functions with parameters
Void functions without parameters:
We can write a function without any parameters. Here, greeting function receives nothing and returns nothing.
//function declaration
void greeting(void);
int main(void)
{
// statements
greeting(); //call
return 0;
} //main
void greeting(void)
{
print(“hello world:”);
return;
} //greeting
If the void function does not have a value, it can be used only as a statement; it cannot be used in an expression.
Void functions with parameters:
Let’s call a function that has parameters but still returns void. Since this function returns nothing to the functions, main, its return type is void.
//function declaration
void printone(int x);
int main(void)
{
//local declarations
int a=5;
//statements
printone(a); //call
return 0;
} //main
void printone(void)
{
printf(“%d\n”,x);
return;
} //printone
Non-void functions without parameters:
Some functions don’t have any parameters but return a value.
//function declaration
int getquantity(void);
int main(void)
{
//local declaration
int amt;
//statements
amt = getquantity();
...
return ();
} //main
int getquantity(void);
{
//local declaration
int qty;
//statements
printf(“Enter quantity”);
scanf(“%d”,&qty);
return qty;
} //getquantity
The most common use for this design reads data from the keyboard or a file and returns the data to the calling program.
Non-void functions with parameters:
The program contains a function that passes parameters and returns a value. Here, square of the parameter is the function. The returned value is place in the variable b, as shown. This is done by the result of expression evaluation and not by the call.
//function declaration
int sqr(int x);
int main(void);
{
//local declaration
int a;
int b;
//statements
scanf(“%d\n”,&a);
b=sqrt(a);
printf(“%d\n”,a,b);
return 0;
} //main
int sqr(int x);
{
//statements
return(x * x);
} //sqr