C Macro

Summary: in this tutorial, you will learn about C macro. We will show you two different kinds of macros in C including object-like macros and function-like macros.

C Macros

What is a C macro

A C macro is a piece of code that has a specific name called macro name. Whenever the macro name is used, C preprocessor will replace it with the body of the macro. C allows you to define a macro for any valid identifier, even C keyword.

C provides you with two kinds of macros: object-like macros and function-like macros.

Let’s examine each type of macro and context where you are going to use it.

Object-like macros

An object-like macro is an identifier that will be replaced by a sequence of token ( or piece of code) in the program. As its name implied, the object-like macro is similar to data object in code in term of its usage. You typically use an object-like macro to give a meaningful name to a constant.

To define a new macro in C, you use the #define directive. The syntax of the object-like macro is as follows:

In the syntax above:

  • You use the #define directive followed by the macro name ( macro_name) and macro body ( macro_body).
  • Macro body is a token sequence that macro name stands for. The macro body is also known as replacement list or expansion.
  • No semicolon ( ;) is used at the end of the statement.

The following example creates a new object-like macro:

The macro name is MAX_SIZE and it is abbreviated for the constant 1000. From now on, you can use this macro “like” an identifier in code such as:

The C preprocessor will replace the MAX_SIZE by 1000 as follows:

By convention, you put the macro name in uppercase to make your code is easier to read and maintain.

You can define a macro onto multiple lines using backslash-newline. C preprocessor will treat it as one line when the macro is expanded, for example:

Another important point you should keep in mind that C preprocessor processes program sequentially. Therefore, the macro is effective from the position where it is defined. Consider the following example:

The value of x is 100.

Function-like Marcos

C also allows you to define a macro that look like a function call. Therefore, this macro is referred as a function-like macro.

The syntax of creating a function-like macro is similar to object-like macro except you have to put the parentheses () right after the macro name.

The following example demonstrates how to use function-like macros:

In the code, the preprocessor only replaces function-like macro when the macro name appears with the parentheses () right after it.

In this tutorial, you have learned how to create two different kinds of macros in C: object-like macro and function-like macro. It is important to use C macro properly to increase your code readability.

  • Was this tutorial helpful ?
  • YesNo