Defined Types and Data Structures
Defined Constants
- The #define preprocessor directive can be used to globally replace a word with a number.
- It acts as if an editor did a global search-and-replace edit of the file.
- So for example, if you have:
#define MAXARRAYSIZE 100
then everywhere that the preprocessor finds MAXARRAYSIZE, it will replace it with 100. So:
int numbers[ MAXARRAYSIZE ];
for( int i = 0; i < MAXARRAYSIZE; i++ )
become:
int numbers[ 100 ];
for( int i = 0; i < 100; i++ )
Beware of two common errors with #defines - Adding extra characters that don't belong. For example:
#define MAXARRAYSIZE = 100
#define MAXARRAYSIZE 100;
results in :
int numbers[ = 100 ];
int numbers[ 100; ];
Leading to the unexpected error messages:
- Error: = not expected
- Error: missing ]
Preprocessor defines can incorporate previously defined variables, as in:
#define PI 3.14159
#define PI2 ( PI / 2.0 )
Function Prototypes
- Adding
function prototypes into header files ensures that all functions agree on what the prototype should be, and if it changes, it only needs to be changed in one place.
Declared ( not Defined ) Global Variables
- The "extern" keyword on a global variable declaration lets the compiler know that the variable exists, but does not allocate any space for it.
- Exactly one file in the program must define the variable ( allocate space and initialize if appropriate ), by declaring it without the extern keyword.
- So in the .h file that is #included by everybody:
extern int maxAssignments, maxScores[ ]; // Note no size given for the array
and then in exactly one .c file:
int maxAssignments = 7, maxScores[ maxAssignments ]; // Here a size is required and initialization is allowed
Macros
- Macros are a lot like functions, only different. They will be covered sepaately.