0
#include<stdio.h>
#include<stdlib.h>

#define d 10+10

int main()
{
    printf("%d",d*d);
return 0;
}

I am new to the concept of macros.I found the output for the above program to be 120.What is the logic behind it?

Thanks.

1
  • 2
    Use cpp source.c to see how is expanded Commented Jan 15, 2013 at 20:03

8 Answers 8

5
10+10*10+10 == 10 + 100 + 10

Is that clear?

3

Macros are replaced literally. Think of search/replace. The compiler sees your code as 10+10*10+10.

It is common practice to enclose macro replacement texts in parentheses for that reason:

#define d (10 + 10)

This is even more important when your macro is a function-like macro:

#define SQ(x) ((x) * (x))

Think of SQ(a + b)...

1

d*d expands into 10+10*10+10. Multiplication comes before addition, so 10 + 100 + 10 = 120.

In general, #define expressions should always be parenthesized: #define d (10+10)

1

A macro is a nothing more than a simple text replacement, so your line:

printf("%d",d*d);

becomes

printf("%d",10+10*10+10);

You could use a const variable for more reliable behaviour:

const int d = 10+10;
1

The macro is expanded as is. Your program becomes

/* declarations and definitions from headers */

int main()
{
    printf("%d",10+10*10+10);
return 0;
}

and the calculation is interpreted as

10 + (10 * 10) + 10

Always use parenthesis around macros (and their arguments when you have them)

#define d (10 + 10)
1
#define 

preprocessor directive substitute the first element with the second element.

Just like a "find and replace"

1

I'm not sure about #include but in C# #define is used at the top to define a symbol. This allows the coder to do things like

#define DEBUG

string connStr = "myProductionDatabase";

#if DEBUG
    connStr = "myTestDatabase"
#edif
0

10+10*10+10 = 20 + 100 = 120

Simple math ;)

Macro doesn't evaluate the value (it doesn't add 10 + 10) but simply replaces all it's occurences with the specified expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.