C macros, you should know

In C macros is a segment of the code which has some unique name. Whenever in a program we used the macro name, it is replaced by the contents of the macro.

These replacements occur before the compilation of the code that is the reason there is no type checking occur with macro in C. Basically, there are two types of macros, object-like macros, and function-like macros.

Object-like Macros in C

An object-like macro is a simple identifier which will be replaced by a code segment (piece of code) in the program. It mainly used to give a symbolic name to a numeric constant and it is a good habit to give a meaningful name to a numeric constant.

Like if you are creating a macro to represent the second, you should write the macro name SECOND. It increases the code readability.

To define a new macro in C, We can use the #define. A #define is a pre-processor directive.

Syntax of the object-like macro,

 

For Example,

 

Now ARRAY_SIZE is an alias of 1024, whenever in the program we will use ARRAY_SIZE it replaces with 1024.

 

Before the compilation of the code, C pre-processor will replace the ARRAY_SIZE with 1024 and the array will look like the below expression,

 

An object-like macro could have multi-line. So to create a multi-line macro you have to use backslash-newline. See the below example,

OutPut:

arr[0] = 10
arr[1] = 20
arr[2] = 30

If you want to learn more about the c language, here 10 Free days C video course for you.

C tutorial

Function like macro in C:

A function like macro looks like the function is because it has a pair of parentheses like the function. Similar to the object like macro #define use to create a function like macro. You need to put a pair of parentheses immediately after the macro name.

For example,

 

Output:

Max value 20

You can See, Token Pasting Operator

 

You should remember following points before using the function like macro in c.

  • Always use proper parentheses in macro.
  • Use each macro parameter once to avoid the undesired side effect.
  • You should never use a function like macro if you can use the function.
  • Always remember there is no type checking occur in macro.
  • You should remember following points before using the function like macro in c

We can also create function like macro in multi-line, See the below example in which I am swapping the value of two variable.

c macro in c

 

You can See, typedef vs #define

 

Some C Predefined Macros

 

See the example code,

Output:

File Name :pointermain.c
Current Date(MM DD YYYY) :Jan 1 2019
Current Time(HH:MM:SS) :14:34:08
Line Number :11



One comment

Leave a Reply