Functions...
What is a Function?
- A repeated section of code
- Functions can accept zero or more parameters in a parameter list
- Parameter list is delimited by parenthesis
- Functions may return a single value or no value
- Sections of repeated code should be placed into functions to keep the code clean and make the meaning clearer
- Functions should always be declared before they are defined or used - if you call a function before it has been defined in the source code it will not work
- Functions usually defined in a header file (.h)
- Need to declare the return type (or void), the function name, and the parameters (if any)
Function Declaration Syntax:
int add (int num1, int num2);
int add (int num1, int num2);
- return type
- name of function
- parameter list
- semicolon indicates that this function header is a declaration which will be defined later - the definition will be in the C file
Function Definition Syntax:
int add (int num1, int num2)
{
return num1 + num2;
}
int add (int num1, int num2)
{
return num1 + num2;
}
- return type
- name of function
- parameter list
- function statements (between curly braces)
Return Type:
- A function can return any scalar value or a pointer
- If a function does not return a value, specify a return value of 'void'
Parameters:
~ the value of a variable is passed to the function
~ the function can not modify a parameter passed by value
2 - By a reference:
~ the address of a variable is passed to the function
~ the function can modify a parameter passed by reference
example: scanf( );
- Parameters may be passed to a function in two ways:
~ the value of a variable is passed to the function
~ the function can not modify a parameter passed by value
2 - By a reference:
~ the address of a variable is passed to the function
~ the function can modify a parameter passed by reference
example: scanf( );
Pointers:
1 - To declare a pointer value
int a = 5;
int *pa;
2 - To obtain or set the contents of a pointer
int b = *pa;
pa = &a;
Note:
In the C language it is very common to have a variable name that starts
with 'p' - naming convention used to represent a pointer.
- Indirection Operator (*)
1 - To declare a pointer value
int a = 5;
int *pa;
2 - To obtain or set the contents of a pointer
int b = *pa;
- Address-Of Operator (&)
pa = &a;
Note:
In the C language it is very common to have a variable name that starts
with 'p' - naming convention used to represent a pointer.