Functions in C

Functions

Functions are subprograms that perform some operation and return one value

They "encapsulate" some particular operation, so it can be re-used by others (for example, the abs() or sqrt() function)

Functions in C

Characteristics

Reusable code.

code in sqrt() is reused ofter

Encapsulated code.

implementation of sqrt() is hidden

Can be stored in libraries

sqrt() is built-in function found in the math library

Functions in C

Writing Your Own Function

Consider a function that converts temperatures in Celsius to temperatures in Fahrenheit

Mathematical Formula

F = C * 1.8 + 30.0

We want to write a C function called CtoF

double cToF(double cel){
	return cel * 1.8 + 32.0;
}
			

This function takes an input parameter called cel(temp in degree Celsius) and returns a value that corresponds to the temp in degree Fahrenheit

Functions in C

How to use a function?

#include <stdio.h>
double cToF(double);
void main(){
	double c, f;
	printf("Enter the degree(in Celsius");
	scanf("%lf", &c);
	f = cToF(c);
	printf("Temparature (In Fahrenheit) is %lf\n", f);
}
double cToF(double cel){
	return cel * 1.8 + 32.0;
}
			
Functions in C

Terminolory

Declaration:

double cToF(double);

Invocation (Call):

f = cToF(c)

Definition

double cToF(double cel){
	return cel * 1.8 + 32.0;
}
			
Functions in C

Function Declaration

Also called funciton prototype

syntax: return_type function_name(parameter_list)

Example: double cToF(double)

Declarations describe the function:

the return type and function name

the type and number of parameters

Functions in C

Function Defination

Syntax

return_type function_name(parameter_list){
	....
	function body
	...
}
			

Example

dobule cToF(double cel){
	return cel * 1.8 + 32.0;
}
			
Functions in C

Function Invocation

void main(){
	double c, f;
	printf("Enter the degree(in Celsius");
	scanf("%lf", &c);
	f = cToF(c);
	printf("Temparature (In Fahrenheit) is %lf\n", f);
}
				
1. Call copies argument c to parameter cel
2. Control transfers to function cToF
double cToF(double cel){
	return cel * 1.8 + 32.0;
}
				
Functions in C

Function Invocation

void main(){
	double c, f;
	printf("Enter the degree(in Celsius");
	scanf("%lf", &c);
	f = cToF(c);
	printf("Temparature (In Fahrenheit) is %lf\n", f);
}
				
3. Expression in "cToF" is evaluated
4. value of expression is returned to "main"
double cToF(double cel){
	return cel * 1.8 + 32.0;
}
				
Functions in C

Local Objects

The parameter "cel" is a local object which is defined only while fucntion executing. Any attempt to use "cel" outside the function is an error

The name of the paramenter need not be the same as the name of the argument. Types must agree.