Notes on macros in C

Synopsis

#define NAME expression

It’s standard convention in C that #define statements are defined with UPPERCASE names, although this is not required.

The preprocessor essentially does a “find and replace” with all #define statements substituting their key with it’s expression.

Therefore

#define MY_NAME "Jon"
printf(MY_NAME);

Is seen by the compiler as

#define MY_NAME "Jon"
printf("Jon");

This is why #define statements do not have terminating semicolons. See an example of why below:

#define MY_NAME "Jon";
printf(MY_NAME);

Would be interpreted by the compiler as

#define MY_NAME "Jon";
printf("Jon";); 

It’s common for #define statements to be defined at the start of a program, like so:

#include <stdio.h>

#define MY_NAME "Jon"
#define NUMBER_THREE 3

int main(int argc, const char * argv[])
{
    //...
}

However, this is not required – they can be defined anywhere within a program, so long as they’re defined before they’re referenced.

Scope

#define statements are always global, regardless of whether they have been declared inside or outside of a function.

Leave a Reply

Your email address will not be published. Required fields are marked *