The Importance of Brackets When Defining Macros

In C programming, there are some points to be careful while using “#define” macro. One of them is use of brackets because these macros do not work exactly how in the mind of humans. If you see lots of useless paranthesis in others codes you should read this article.  Macros do exactly what you want from them without examining and calculating. Without further ado, let me give an example of some codes:

#include 
#define ABS(x) x>0?x:-x

int main()
{
    printf("%d\n",ABS(3-5));
    return 0;
}

In this code segment the macro called ABS, if the value sent to it is less then 0 puts “-” sign in front of this value, else leaves it as it is. In short, the absolute value. The expectation is +2 because 3-5=-2. However, the value which is sent to macro is not -2 but 3-5. The difference is that macros do not calculate the argument and work with the result, like functions. Macros works like dictionaries. Just before the compile they make the modifications and finishes their jobs, like in the basic notepad programs, find and change module (ctrl+h). After this tip, analyzing the ABS macro again shows us putting “-” sign in front of the 3-5 gives -3-5 which is equal to -8. In fact,there is nothing to be surprised, is there? :) Then, here is the solution:

#define ABS(x) (x)>0?(x):-(x)

If we defined the macro with paranthesis, there would not be any problem. Another example is;

#include 
#define SQR(x) (x*x)
int main()
{
    printf("%d\n",SQR(2+3));      
    return 0;
}

I do not make same explenations again and again. The expectation is 2+3=5, so the result is 5*5=25. Whereas SQR turns 2+3 value into 2+3*2+3. It is same with 2+(3*2)+3 in maths, so with 11 not 25.

#define SQR(x) ((x)*(x))

Defining the macro with useless(!) brackets, makes all c programmers happy. :)

Leave a Reply

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


9 + 1 =