Lect16 PDF
Lect16 PDF
Functions
Functions in C
Function Definition
return-value-type function name (paramter-list) {
declarations
statements
}
Functions in C
Return from Function
Only one function with a given name is allowed
A function returns (control restored back to caller) when either
A return is encounter during execution of the function code, or
The control reaches end of the function body
Argument Conversion
C allows function calls even if argument types do n’t match with
corresponding parameter types.
The rules for type conversion of arguments depends on whether
function prototype is encountered not prior to call or not.
Functions in C
Argument Conversion
Prototype seen prior to call Prototype not seen priort to call
Each argument implicitly Default argument promotion is
converted into type of performed.
corresponding parameter as if by
assignment float coverted to double
Eg., int type converted to Integral promotion are
double if function expects performed, causing short or
double. char converted to int
Functions in C
Relying on default promotion is dangerous.
#i n c l u d e < s t d i o . h>
i n t main ( ) {
double x = 5 . 0 ;
/∗ No p r o t y p e s e e n . Not known i f i n t i s e x p e c t e d . ∗
∗ D e f a u l t p r o m o t i o n t o d o u b l e i s o f no e f f e c t ∗
∗ Result i s undefined ∗/
Functions in C
Without Parameters & Return Values
#i n c l u d e < s t d i o . h>
void f a c t o r i a l () {
int n , r e s u l t = 1;
p r i n t f (” Enter n : ” ) ;
s c a n f ( ”%d” , &n ) ;
p r i n t f ( ”%d ! = ” , n ) ;
while ( n > 0 ) {
result = result ∗ n;
n−−;
}
p r i n t f ( ”%d\n” , r e s u l t ) ;
}
i n t main ( ) {
factorial ();
}
Functions in C
Void Type
Void is not a type.
Syntactically it is used where a type name is expected.
When used for parameter-list: function does require any
parameters.
Eg., int function(void) is same as int function().
If return type not mentioned function always returns int, i.e.
function() same as int function()
Functions in C
Void Type
Void type introduced so that compiler can issue a warning when a
function does not return an integer type if that is supposed to return
one.
A variable declared void is useless.
But, void * defines generic pointer. (Any pointer can be cast to void
pointer and back without loss of information)
Functions in C
Function with a Return Value
#i n c l u d e < s t d i o . h>
int f a c t o r i a l ( int n) {
int r e s u l t = 1;
while ( n > 0 ) {
result = result ∗ n;
n−−;
}
}
i n t main ( ) {
int n;
p r i n t f (” Enter n : ” ) ;
s c a n f ( ”%d” , &n ) ;
p r i n t f ( ”%d ! = %d\n” , f a c t o r i a l ( n ) ) ;
}
Functions in C
Function with a Return Value
read n
Functions in C
Decimal to Binary
#i n c l u d e < s t d i o . h>
i n t binaryNumber ( i n t n ) {
i n t r = 0 , s =1;
w h i l e ( n !=0) {
i f ( n % 2 != 0 )
r = r + s;
s=s ∗ 1 0 ;
n=n / 2 ;
}
return r ;
}
i n t main ( ) {
p r i n t f ( ” B i n a r y o f %d i s %d\n” , 5 8 , b i n a r y N u m b e r ( 5 8 ) ) ;
}