Files
freeCodeCamp/guide/english/c/macros/index.md
Pawan Bangar 9e5d2baac1 ADD "Undefining Macro" (#21287)
* ADD "Undefining Macro"

we can undefine macro whenever we want in code by adding #undefine

* fix: markdown title format

* fix: minor grammar corrections

Capitalise first word and remove extra full stops
2018-11-08 19:22:35 +00:00

1.7 KiB

title
title
Macros in C

Macros in C

A macro is a piece of code with a given name. When the name is used, it is replaced by the content of the macro.

Defining macros

The #define keyword is used to define new macros. It's followed by a name and a content. By convention, macro names are written in uppercase.

#define PI 3.14

If you use the macro this way:

printf("Value of PI: %d", PI);

Is the same as write this:

printf("Value of PI: %d", 3.14);

Undefining Macros

After defining macros you can also undefine them at any point. just Type

#undefine PI

This is used to use macros only for specific lines of code and again undefine it.

Types of macros

There are two type of macros. The Object-like macros, showed above, and the Function-like macros.

Function-like Macros

Function-like uses the same #define keyword. The difference is that you use a pair o parentheses after the function name.

#define hello_world() printf("Hello World!")

So calling:

hello_world()

You get:

printf("Hello World!");

You can set parameters too:

#define hello(X) printf("Hello " X "!")

Now calling:

hello("World");

You get the equivallent of:

printf("Hello World!");

More Information:

GCC Online Documentation: Macros

GCC Online Documentation: Object-like macros

GCC Online Documentation: Function-like macros