You are on page 1of 3

Functions and file organization

1. Functions must be defined before they are used


2. Write a function declaration/function prototype near the start of the program, write the
implementation later in the file
The function prototype must have the same types of parameters and the same number of
parameters as the implementation (It is acceptable to omit the variable names in the function
prototype)

3. It is much better to place all the function prototypes in a header file (.h extension)
Place all the function implementations in a file (preferably with the same name) but a .c
extension

Have an include guard to present multiple includsion. Include guard is typically set out as:

#ifndef FILE_NAME_H
#define FILE_NAME_H

....//the prototypes

#endif

Static & Extern:


1. When a variable in a FUNCTION is declared as static, it is only initialised the first time the
function is called. Its value preserved between function calls. It's lifetime extends beyond a
function call.

2. When a FUNCTION or global variable is declared as static in a FILE, that function or global
variable is only known in that file.

3. When a global variable is declared as extern, it means it is a global variable declared in


another file. It is a means to share global variables between different files.

Passing parameters
Passing parameters by value: When a parameter is passed to a function by value, the function
receives a copy of the parameter. Local changes do not affect the original value
Example
void passByValueExsmple(int a)

Call as passByValueExsmple(x)
Passing parameters by reference:
A reference is passed to the function. Changes to the variable affect the passed copy.
Eg
void passByRefExample(int *a){
*a= * +4; //use *a in the code
}

Call as passByRefExample(&x);

Enum
Enum is a user defined type that gives names to integer values. eg

enum states {wash, rinse, spin, stop};

declare a variable named machine_state as enum states machine_state;

You can assign a value to the variable eg machine_state =rinse

the variable can be used wherever an integer could have been appropriate, eg in a switch
statement.

eg

switch (machine_state){

case stop: printf "stopped"; break;

case rinse: printf "rinsing"; break;

case spin : printf "spinning"; break;

default: printf("unknown state");

A very useful feature in designing embedded systems.

You might also like