return_type function_name (parameter list)
{
body of the function
}
The return_type is the type the function returns
Some functions do not return values, in this case void is used
The function name and the parameter list together constitute the function signature
a function may contain no parameters
The function body contains a collection of statements that define what the function does
call by value
The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function
changes made to the parameters inside the function have no effect on the arguments
void swap (int x, int y);
int main (){
int a = 100, b = 20;
printf("Before swap, value of a : %d\n", a);
printf("Before swap, value of b : %d\n", b);
swap(a,b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap (int x, int y) {
int temp = x;
x = y;
y = temp;
}
call by reference
The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter
Inside the function, the address is used to access the actual argument used in the call
changes made to the parameter affect the passed argument
To pass by reference, argument pointers are passed to the functions just
the function parameters need to be declared as pointer types
void swap (int *x, int *y);
int main (){
int a = 100, b = 20;
printf("Before swap, value of a : %d\n", a);
printf("Before swap, value of b : %d\n", b);
swap(&a,&b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap (int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
Memory Layout - Stack
The stack segment is the area where local variables are stored
local variable are declared in every function including main() in C program
When we call any function a stack frame is created
function returns, stack frame is destroyed including all local variables of that particular function
Stack frame contain some data like return address, arguments passed to the function, local variables,. . .
A “stack pointer (SP)” keeps track of stack by each push and pop operation onto it
Arrays
Array a fixed-size sequential collection of elements of the same type
An array is used to store a collection of data of the same type
All arrays consist of contiguous memory locations
The lowest address corresponds to the first element and the highest address to the last element