C Preprocessor

We can use the #define statement to define a constant. The #define statement, like all preprocessor commands, begins with a hashtag.

#include <stdio.h>

#define INDEX_SIZE 10

int main(void){
    
    int i = 0;
    
    int dataArray[INDEX_SIZE];
    
    while(i++ < INDEX_SIZE){
        dataArray[i] = 1 + i; 
    }
    
    for(i = 0; i < INDEX_SIZE; i++){
        printf("%d\t", dataArray[i]);
    }
    
    putchar('\n');
    
    
    
    return 0;
}

Note that unlike a regular C statement, a preprocessor directive terminates at the end-of-line. This is different from normal C statements that end in a semicolon.

The #define statement works by creating a replacement macro. The replacement macro is a string of text with an associated value; wherever this string of text appears in the program it is replaced by its associated value. It is considered best practice to use all uppercase letters for macro names.

#include <stdio.h>

#define NUMX 10
#define NUMY NUMX + 10
#define NUMZ (NUMX + 10)

int main(void){
    
    printf("NUMX = %d\n", NUMX);
    printf("NUMY = %d\n", NUMY);
    //does not give the answer we 
    //were expecting
    printf("NUMY^2 = %d\n", NUMY * NUMY);
    printf("NUMZ = %d\n", NUMZ);
    //this does give the answer
    //we were expecting
    printf("NUMZ^2 = %d\n", NUMZ * NUMZ);
    
    return 0;
    
}

Be careful, as the macros are replaced exactly as they are written.

One of the best uses of the preprocessor is in conditional compilation, which depends on the #ifdef and #endif statements.

#include <stdio.h>

#define LIFE 42

int main(void){
    
    //will be compiled
#ifdef LIFE
    printf("The meaning of life is %d\n", LIFE);
#endif
    
    //won't be compiled
#ifdef BESTNUMBER
    printf("The best number is %d\n", BESTNUMBER);
#endif
    
    return 0;
    
}

There are two more preprocessor directives for us to look at, the #ifndef and #else directives. Unlike #ifdef, #ifndef will cause the code to be compiled only if the macro is not defined.

#include <stdio.h>

#define BOOMER 1
#define MONKEY 2


int main(void){
    
#ifdef BOOMER
    printf("Boomer lives!\n");
#else 
    printf("What about Boomer?\n");
#endif
    
#ifndef LAFONDA
    printf("Marc Maron's other cat is named LaFonda\n");
#endif
    
    return 0;
    
}

If you’re interested in learning more about C, have a look at my book filled with 100s of unique example programs coupled with succinct explanations: http://www.amazon.com/Big-Als-C-Standard-ebook/dp/B00A4JGE0M/

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s