|
~ Introduction to Programming: C ~ Session 2 - Libraries, Main Function and Curly Brackets |
In This Session...
In this session we will be covering the following topics:-
Every C program you write will have some key parts which we will investigate during this session.
Create a new project called numbers.mak, starting with a blank page. Type out the following C source code:-
#include <stdio.h>
#include <conio.h>
void main()
{
int a,b,c;
a=1; b=1; c=a+b;
printf("a+b=%d\n",c);
printf("Press a key to finish.");
getch();
}
Over the next two weeks, we will go through the main parts of this program to better understand what is going on, and try changing a few things to see what happens. Briefly, the sections are :-
Including Library files - identify libraries where data is held
Main function - identify what instructions will be executed first
Variable declarations - identify boxes to put information into
Variable assignment - put values into these boxes
Printf function - Displaying variable contents and text together
getch function - Waiting for a character to be pressed
Introduction to Libraries and functions
In everyday life, if you wanted to find out how to do something, a good bet is to pop into your local library and take out a book on the subject. For example, if you wanted to know how to put up a poster saying "Hello World!" you might look in the arts section and find a book called "putting up big messages". The great thing about books is that someone else has done what you want to do before, and has helpfully written a book about how to do it!
So what does this have to do with C?
The C language just gives you a limited number of keywords or commands to tell the computer what to do. The rest you have to make up yourself. Understandably, there's a whole host of things that people who use C regularly have to do, so why not write the programs to do common tasks once, and store them away with a name so that you can use them again and again in any future programs?
In C, these pre-written tasks are known as functions. Each function is given a name both to identify it, and to distinguish it from other functions - e.g. 'printf' to write something onto the screen (it could have been called print_something_to_the_screen, but printf saves typing! - it means "print formatted"). This is a bit like giving our book (that contains instructions telling you how to do a particular task) a suitable name so we can identify it when we next need to use it.
Note that functions can do a specific fixed task, or can take
Functions that are related (e.g. functions that relate to maths-related tasks) are grouped together and stored in the same place (a bit like the "Arts" section in your public library). Each of these sections is known as a library or function library.
So, to make use of these pre-written tasks (functions), you need to tell C in which section (library) to look to do the task, and the name of the book containing the instructions you need (function name).
The C Compiler needs to know where to look for the functions that you use in your program, so you need to list the libraries that you will be using at the top of your program. Imagine the situation in your library where you have to look for a book on "putting up big messages" when the library has no "Arts" section - just row upon row of mixed-up books! Aargh! Telling the compiler where to look speeds things up for the computer, and also reduces the risk of having the same title that does two different jobs (the book "multiplication" might be in the "Maths" section, but also in the "Wildlife" section amongst other bunny-rabbit books!)
In our example, the two lines that tell us which libraries we will be looking in to use specific functions are:-
#include <stdio.h>
#include <conio.h>
Note that any instructions that start with a # take up a whole line, and finish at the end of the line. This is different to how the rest of C works - more on this in a future session when we deal with pre-processing.
The #include instruction or keyword tells the computer that we wish to include the stdio.h and conio.h libraries in our program in order to use them.
Files ending with .h are what are known as header files, giving a description of what functions are available without listing the instructions that make-up each individual function (a bit like a contents page in a book that gives an overview of a particular topic). We will not be making our own header files on this course.
So what are stdio.h and conio.h?
stdio means "standard in/out" which means a standard way of getting data to and from input and output devices. In our case, we wish to take data in from the keyboard (a standard input device) and put data onto the screen or console (a standard output device).
conio means "console in/out" which means ways of getting data to and from the console device (which uses the keyboard and screen).
On the surface, both libraries seem to cover the same sort of function - and for our purposes, they do. However, stdio.h is more generalised, and (as we will see later) can be used to read/write data from/to a disk file for permanent storage of data, write data out to a printing device, and so on. The conio.h library just contains functions that deal specifically with the console (keyboard and black pop-up screen).
Try taking out the following line from the program:-
#include <conio.h>
Try to run the program. What happens? Can you guess why? Which library do you think the function called getch() is kept in?
Put the line back in again and run the program again. Does it work again?
If you make a mistake in your program, the computer will highlight the line where it thinks things have gone wrong (it doesn't always work this out correctly, so be warned!)
In the above exercise, the following line was highlighted:-
getch();
At the bottom of the screen, a message appeared saying:
(C++ Error) numbers.cpp(15): Call to undefined function 'getch'.
This means that there is a problem in the program 'numbers.cpp' at line 15. The reason given is rather cryptic - "Call to undefined function 'getch'". This means that the compiler was looking for a function called getch but couldn't find it. This is because the getch function is specifically designed for getting a character from the console (the keyboard), and is therefore kept in the conio.h libary. Taking out the line to include access to the conio.h library means that the C Compiler can no longer 'see' the function. It is the equivalent of putting a 'no entry' sign around the 'Console functions' section!
You can create functions inside your program to split it up into sections - e.g. a function called printHeading, another called calculateResults, and another called waitForKey. We won't be doing that just yet, but this does introduce a problem - which function do we start to execute first when we run the program. Where is our first instruction to give the computer?
The first function that gets executed is called main - you must ALWAYS include this in your program, otherwise the computer doesn't know where to start!
In our example, the main function is declared (i.e. identified) as follows:-
void main()
{
}
Remember that a function can have data fed into it, and can feed a result back out when it has finished performing its task. In our case, we do not want to feed any data out, hence we use the keyword void to show that nothing is to be fed out (in computerspeak, we say that no value is returned). The parentheses or brackets () after the name main having nothing inside them. This means that nothing is to be fed into the main function.
If you find this hard to follow, don't worry. Just make sure your have a main function in your program as shown above.
After declaring the main function, we have put an opening curly bracket after the end of the main() function, and then a number of instructions follow. When these instructions are finished, a closing curly bracket shows the end of the instructions.
Curly brackets group together a set of instructions - in this case, we are grouping together all the instructions under the function name main. You can read them as follows:-
Opening Curly Brace { - Beginning of instructions for the main function
Closing Curly Brace } - End of instructions for the main function
We show where the end of an instruction is by placing a semi-colon (;) character straight after each instruction. This makes programming very much a step-by-step process, with each step being a command with a semi-colon on the end of it.
In the next session we will be covering the following topics:-
More on mathematics and statistics: Precedence, Parentheses, Totals, Percentages and Averages. Integers and reals. Casting
More on Printf
Introduction to using scanf for keyboard input
Introduction to debugging.
![]()
(c) Copyright
2002-4 Simon Huggins. All Rights Reserved.
If you have any issues or questions regarding the content of this web
site, please contact the
author by clicking here.
Alternatively, you can leave a voice message on 00 44 (0)7050-618-297 or fax
on 00 44 (0)7050-618-298
This Page was last updated: 29 January 2004 13:06