Preprocessor Directive to Include Another File at the Current Point in the Program
Total Page:16
File Type:pdf, Size:1020Kb
CSE230CSE230
CC PreprocessorPreprocessor
#include
1 • Preprocessor directive to include another file at the current point in the program • #include “file.h” locate file.h in current directory (can use a full UNIX path name) • #include
#define • Preprocessor directive that replaces every occurrence of the specified identifier by the replacement string in the remainder of the file #define PI 3.141592 #define EOF (-1) #define EQ == #define SQR(x) ______#define BAD_SQR(x) x * x #define WORSE_SQR (x) ______; #undef EQ Example • Macro that finds the maximum of 3 values #define max(x,y) ______#define max3(x,y,z) max(max(x,y),z) • If #define cannot fit on one line, use backslash at end of first line to continue macro on next line • To view results of preprocessor without compilation: gcc -E file.c
Preprocessing Operators
2 • #define greeting(m) \ printf(#m)
/* In main(): */ greeting(Hello World!); • #define X(i) x ## i /* In main(): */ ______= ______; Conditional Compilation • Allows certain sections of code to be compiled if a condition is met • #define DEBUG /* ______*/ #ifdef DEBUG /* debugging code goes here */ #endif /* ______*/ More Conditional Compilation • #if defined(SUNSPARC) /* ______*/ #else /* ______*/ #endif • #if ndef(PI) float PI = 3.141592; #endif
More Conditional Compilation(cont’d)
3 • Prevent multiple inclusion of header #ifndef SomeName #define SomeName
/* declarations and code here */
#endif
Assert • Generally used for debugging to test preconditions • assert is a macro (see page 389)
#include
#define swap(x,y) \ { ______}
#define N 11 #define MAX 1001
Quicksort Program
4 int main(void) { double a[N]; int i; srand(time(NULL)); for (i=0; i < N; ++i) a[i] = (rand() % MAX)/10.0; quicksort(a, a+N-1); for (i=0; i < N; ++i) printf(“%lf\n”, a[i]); return 0; } Quicksort Algorithm void quicksort(int *left, int *right) { int *p, *pivot; if (left < right) { pivot = left; p = partition(left, right, pivot); quicksort(left, p-1); quicksort(p+1, right); } } Quicksort: Partition int *partition(int *left, int *right, int *pivot) { while (left <= right) { while (*left < *pivot) ++left; while (*right > *pivot) --right; if (left 5