Getting Started

(lily) #1

Chapter 6: C Functions and Program Structures


An example bug comes when you create an extern:


extern int upcount;

onths,

plementation

equal to some value, external and static
e initialized to zero; automatic and register variables
d to random garbage. It’s good practice to always

in file1 and declare it in files 1 and 2 and put your code aside for a few m
then get busy on file3 and decide that you need an external variable to do some up
counting, so you declare it int upcount = 0; forgetting that it has already been
declared as an extern in file1 which you have stuck in a library and no longer look
at. Then you start getting weird bugs where the seemingly impossible event
occurs that your upcount is getting changed unpredictably. This kind of error is so
common that it was one of the reasons C++ was invented. Use externs if
absolutely necessary (sometimes nothing else will do) but use them with extreme
caution.


Headers..........................................................................................................


Header files are a convenient place to stick all the stuff that you put before the
main() function. They are files with a suffix of .h and are declared as:


#include <LEDblinker.h>
#include “PCcomm.h”


If the declaration uses the compiler looks in an im
defined location, usually an ‘include’ directory. If it uses “filename” the compiler
looks in the same directory that the source program was located. The choice will
depend on how you’ve decided to organize your development file system.


Blocks............................................................................................................


Initialization


If you don’t explicitly set a variable
variables are guaranteed to b
are guaranteed to be initialize
initialize a variable.


External and static variables must be initialized with a constant expression, but
you can use other variables in the initialization of automatic and register
variables:

Free download pdf