Professional Documents
Culture Documents
Project Organization
Compiler Directives
A Real C Program
7/28/09
reverse.c - part 1
/** reverse.c
** inputs a single command line argument which is a string
** to be printed with its characters reversed.’
** Use quotes if your string contains spaces
** reverse( ) uses dynamic memory so any size string is ok */
#include <stdio.h> /* printf */
#include <stdlib.h> /* malloc,free */
#include <string.h> /* strlen, strcpy */
7/28/09
reverse.c - part 2
/* main checks the number of args
** then just calls the function to do the work */
return 0;
}
7/28/09
reverse.c
// void reverse (char[ ] s)
void reverse( char *s )
{
char *buf;
int i, sLength = strlen( s );
7/28/09
Compiler directives
7/28/09
#include
The #include directive is used to include the contents of
another file into the file being compiled. It is usually
used to include header (.h) files into the source. #include
files may be nested so that one .h file may #include
another .h file
7/28/09
#define macros
The #define directive may also be used to create a simple macro.
Care must be taken when writing macros and when calling macros
because the arguments are copied literally.
For example, the simple macro below doesn’t work properly in all
instances.
#define SQUARE(x) x * x
Assuming int z = 4, what is the value of y after the assignment
int y = SQUARE( z - 1 );
Nonetheless, macros like this can make code easier to read as we’ll
see later
7/28/09
Importing #defines
• The most common way to #define symbols
is within your .c file
– #define DEBUG
– #define MAX 100
• It is also possible to “import” #defines on
the compiler command line
– gcc -o myProg -DDEBUG -DMAX=100 myProg.c
• You cannot use the command line to
redefine a symbol already defined in
your .c file
7/28/09
assert( )
7/28/09
Conditional Compilation for
Debugging
One simple way of debugging a program is to
insert printf( ) statements are strategic
points in the code. When the program is run,
the output of these printf( ) statements
help you debug your program. When the
program is bug free, these printf( )
statements are removed from your code.
Rather than removing the printf( )
statements by editting your code,
conditional compilation can be used to allow
or prevent them from being executed.
7/28/09
debug.c
#include <stdio.h>
static void debug(char *string)
{
#ifdef DEBUG
printf( “%s\n”, string );
#endif
}
7/28/09
Variable Scope and Lifetime
7/28/09
Local variables
7/28/09
variableScope.c - part 1
#include <stdio.h>
7/28/09
randomInt.c
/* a global variable to be used by code in other .c files.
** This variable exists until the program ends
** Other .c files must declare this variable as "extern"
** holds the random number that was generated */
int randomInt;
/* a function that can be called from any other function
** returns a random integer from 1 to max, inclusive */
7/28/09
randomInt.h
#ifndef RANDOMINT_H
#define RANDOMINT_H
7/28/09