You are on page 1of 7

Elements of a C Program

Comments

Any text placed between the delimeters /* and */ is a comment.

/* a comment */
/* And this
is
another comment */
Programmers insert comments to document a program and improve program
readability. Comments are not part of the executable program, they are ignored by the
C compiler. A good programming practice is to have comments in the program. You
can choose a particular style to highlight comment, for example

/********************************************
* This program generates random numbers in *
* the range 0 - 100 and determines and *
* prints the maximum and minimum numbers. *
********************************************/

int main()
{
...
return 0;
}

Constants

A constant is a value that does not change during the program execution.
Examples of constants are integer numbers such as 0, 10, 23987. These are integer
constants. There are also floating constants, like 3.14159, 2.0, and character constants
like 'a', 'B', etc. Character constants must be included in single quotes and in C
language they are closely related to integers. Any sequence of characters written
between double quotation marks is a string constant. A string constant differs from a
character constant. For example, 'A' and "A" are not the same.

If you use the same constant in your program more than once, usually you will define
it using the #define preprocessor directive.

The #define directive tells the preprocessor to replace every occurence of a particular
character string which is called a macro name with a specified value called a macro
body.

#define macro_name macro_body

The macro body may be a string or a data item.

For example, you may define the maximum number of input values as
#define MAXNUMBER 10

In another program you may define the course name:

#define COURSE_NAME "Computer Science"

Also you may consider to define the logical operators to make the program more
readable:

#define TRUE 1
#define FALSE 0
#define NULL 0
#define AND &&
#define OR ||
#define NOT !

Then you can write a logical expression like this:

if(pass==TRUE)
printf("You passed this subject");

NOTE: 1. # must be the first character on line


2. There is no semicolon at the end of a preprocessor directive
3. Conventionally, names of constants are written in uppercase

Variables

A variable is used to present different values. In the statement such as

i = 1;

the value of a constant 1 is assigned to the variable i. Variable names and function
names in C are called identifiers. To make a valid variable name you can use all the
following:

• Characters A => Z, and a => z.


• Digits 0 => 9, which can be placed in any position except the first.
• The underscore character (_).

Examples of valid identifiers are max_number, var30j, firstName.A variable name


cannot contain:

• arithmetic operators (+, -, /, *, %)


• dots (.)
• apostrophes (')
• other special symbols ( #, ?, ^, etc.)

Examples of invalid identifiers are 4th_number, last-name, quest?.


There are 32 reserved words in C (also called keywords),
which cannot be used as identifiers.
The complete list of C keywords can be found in the reference textbook.

Note that all keywords are written in lowercase letters.

Before a variable can be used in a program statement, it must be declared, for


example:

int number;
char c;
float price;

To declare a variable means to specify its type, for example, integer, with a keyword
int, (types of variables will be discussed later) and name. Variables of the same type
can be declared in one line.

int n1, n2, sum;

To assign a value to the variable, an assignment operator (=) is used, for example i =
1; number = 100; . A variable can be initialised (that is, given an initial value) at the
same time as it is declared.

int number = 0;
char c = 'a';
float price = 2.5;

Expressions

An expression is a combination of constants, variables, operators and function


calls. For example: i + 8 is an expression of a constant plus a variable, and exit(0) is
an expression of a function call. An expression can contain arithmetic and other types
of operators.

C arithmetic operators:

Symbol Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder or modulus

The last operator in this list requires some explanation. The remainder operator % is
used to obtain the remainder of the division of the first operand by the second
operand. For example, 7 % 3 is 1, 8 % 4 is 0, and 5 % 7 is 5

The remainder operator can be applied only to integer constants or variables.


The normal precedence rules are applied to the arithmetic operators, namely, any
expression in brackets is executed first, and division, multiplication and remainder
operations have a higher precedence than addition and subtraction.

Try to work out the following example:

(2+7%2)+45/15-5 = ?

The solution can be obtained if you execute each operation in sequence, taking into
account the precedence rules:

(2+1)+3-5 = 3+3-5 = 1.

Statements

In C language a statement is a complete instruction, ending with a semicolon. For


example, each line of the code below is a statement.

i = 1;
number = (n1 + n2)*12;
hours = seconds/3600;
return 0;

You learned from the example in Program 1 that a function call is also a statement.

printf("This is my first C program.\n");

Any group of statements enclosed in braces ({...}) is called a block. A statement


block is treated as a single statement by a C compiler. This means that anywhere in
the program you can replace a single statement by a block. For example, a while loop
may include a single statement, or a block of statements, as well as if selection.

while(count != MAX)
{ /*block of statements within the while
loop*/
sum = n1 + n2;
diff = n1 - n2;
if(diff > 0) /* single statement after if */
printf("The first number is larger that the second.\n");
}

Functions

Programming modules in C language are called functions. In the First Program we


used the main() function and the C standard library function printf(). Besides using
the standard library functions, you can also write your own functions or use some
functions written by other programmers.

A function definition consists of four parts:


1. The function type indicates what type of value the function returns after its
execution. A function may return a value of any type (see Data types), or may not
return any value.

The default function type of main() function, for example, is an integer. That is why
the C compiler gives you a warning message if the main() function does not have a
return(0); statement at the end. In the example above, the function multiply_int()
returns integer value, which is a value of the integer variable result that is declared in
the first line of the function body.

A function type must match the type of a variable


which is returned by the function.

If a function does not return any value the keyword void is used.

void print_error_message(void)
{
printf("Invalid input. Try again.");
}

This function prints the message on the screen. The first void means that it does not
return any values. The second occurance of the word void indicates that the function
does not take any parameters.

2. The function name should reflect what the function does. For example, the name of
the C standard library function printf() indicates that it "prints formatted data". If
you encounter a function with the name calculate_average(), you would expect that
this function calculates an average value of a set of numbers.

A function name is an identifier, and the same naming rules are applied to names of
functions as to names of variables.

3. A function often requires some information to be passed to it. For example, the
multiply_int() function takes two parameters of integer type. The argument list (or
parameter list) is given in the brackets following the function name, and includes a
list of the types and names of all arguments. Type and name pairs are separated by
commas. The name of a parameter to the function within the function declaration is
called formal, to distinguish it from the actual parameter name, which you use when
making a function call.

If a function does not take any parameters, the keyword void can be used, or the
brackets after the function name remain empty, see, for example, the function
print_error_message() above.

4. A function body is a program block included in braces. It usually contains variable


declarations and C statements (including the return statement if required). One or
more of the statements may be function calls for other functions. However a function
body CANNOT contain a declaration of another function. A good programming
practice is to write functions that perform a single task.

Making Function Calls

To execute a function you make a function call from the other function body. The
function call includes the name of the function and actual parameters in brackets:
function_name(parameter1, parameter2, ...);. For example, the call for the
function multiply_int() can be done as follows.

Program 2.1.

/*Program 2. This program multiplies two integer numbers


and prints the result */

#include <stdio.h>

/* This function returns the result of multiplication of two


integers. */
int multiply_int(int n, int x)
{
int result;
result = n*x;
return result;
}

int main()
{
int product;

product = multiply_int(12, 11);

/* 12 and 11 are actual parameters that are passed to the


function */

printf("The product of 12 and 11 is %d.\n", product);


}

Output:

The product of 12 and 11 is 132


The C compiler must be told about the function you are going to use before you
actually use it. The simplest way is to write all functions' definitions at the top of the
program, ensuring that the function is defined before it is called, like shown in the
Program 2. We will discuss an alternative way to structure a C program that contains
functions in the second part of this course.
Variables scope

A variable declared within a block has a block scope, it is also called a local
variable. A local variable can be accessed only within the block where it was
declared. For example, because the variable result is declared within the
multiply_int() function, it cannot be refered to from the main() function.

A variable is said to have a program scope (or to be an external variable) when it is


declared outside a function. A variable with program scope is considered to be global
to all functions declared after it. After the program control exits from the block or
function, the external variable remains in existance.

Global variables decrease the manageability of a program.


In a large program they may cause untraceable errors.
The use of global variables should be minimised.

Summary:

• A constant is a value that never changes. A variable can present different


values.
• Constants can be defined using the #define preprocessor directive.
• You have to follow certain rules to make valid names of variables.
• An expression is a combination of variables, constants, operators and
function calls.
• A statement is an expression or a function call with a semicolon at the end.
• A statement block may contain more that one statement included in curly
braces({ }).
• The function type of a function indicates the type of the value that the
function returns.
• A function name must be valid and meaningful.
• The parameter list to a function contains types and names of parameters.
• The body of a function is enclosed in curly braces.
• A function should perform a single task.
• A function has to be defined before it is called.
• A local variable is a variable declared within a function.
• Global variables are declared before function definitions.
• The use of global variables should be minimised.

You might also like