CS157: Intro to C, Part II

Spring 2018


See this page as a slide show

CS157 Preprocessor

The C Preprocessor

What the Preprocessor Provides

Constants and #define

    #define NAME value

An Example

#define SIZE 20
#define BAD 10**10
int main() {
    int list[SIZE]; // this is ok
    num = BAD; // not ok, strange error about *
    SIZE = 10; // not ok, SIZE is replaced with 20, error
    BIG_INT = 10000000; // ok, but bad practice

#define BIG_INT long int
    BIG_INT big_num; // ok
    list[0] = BIG_INT; // not ok, BIG_INT is replaced with long int
    return 0;

More about #define


The const keyword tells the compiler that the following variable declaration/initialization will remain constant throughout the program.

const double PI = 3.14159;
PI = 3.0; // This won't work: it's const!

I realize that the concept of a constant variable is a bit of a contradiction. Oh, well!


#define SQR(x) ((x)*(x))


    #define SALES_TAX 0.05



        #define PI 3.14159
        #define CIRCLE_AREA(x) (PI * (x) * (x))
        area = CIRCLE_AREA(4);


Use parentheses. Without them, the macro

    #define CIRCLE_AREA(x) PI * x * x

would cause

    area = CIRCLE_AREA(c + 2);

to become

    area = 3.14159 * c + 2 * c + 2;

Multiple arguments:

    #define RECTANGLE_AREA(x, y) ((x) * (y))
    rectArea = RECTANGLE_AREA(a+4, b+7);


    rectArea = ((a+4) * (b+7));

Conditional Compilation

Making decisions at compile-time.

Conditional Compilation

More #define

    #define DEBUG
    c11 -DDEBUG my_prog.c

More Directives

    #ifdef __HP__
    #define compare stricmp
    #define compare strcasecmp

Conditional Compilation

    #if 0
    	the code that you don’t like


#include <stdio.h>
int main() {
    float friction, number;
    unsigned int zip_code;
#ifndef DEBUG
    zip_code = 13285;
    zip_code = 00001;
    friction = 0.04;
    number = (zip_code * friction) - 3.2;
#ifdef DEBUG
    printf("friction: %f number %f\n",friction,number);
    printf("The final number was %f\n", number);
    return 0;


    #include <file>
    #include "file"


    #include "everything.h"
    #undef PIE
    #define PIE "I like apple."

User: Guest

Edit History Source

Modified: 2018-04-27T14:36

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building