starkk92
starkk92

Reputation: 5924

use of #define in c

#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.

Upvotes: 0

Views: 777

Answers (8)

Matthew Blott
Matthew Blott

Reputation: 209

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

Upvotes: 1

Paolo
Paolo

Reputation: 15847

#define 

preprocessor directive substitute the first element with the second element.

Just like a "find and replace"

Upvotes: 1

pmg
pmg

Reputation: 108988

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)

Upvotes: 1

James M
James M

Reputation: 16728

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;

Upvotes: 1

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221302

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)

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477494

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)...

Upvotes: 3

Adam Sznajder
Adam Sznajder

Reputation: 9216

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.

Upvotes: 0

ouah
ouah

Reputation: 145899

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

Is that clear?

Upvotes: 5

Related Questions