How #define works in Programming when define has value with operator?

I am facing problem to understand how #define works.

#include<stdio.h>
#define x 6+3
int main(){

int i;
i=x;    //9
printf("%d\n",i);
i=x*x;  //27
printf("%d\n",i);
i=x*x*x;   //45
printf("%d\n",i);
i=x*x*x*x;    //63
printf("%d\n",i);

return 0;
}

If I use #define x 6+3 the output is 9 27 45 63

If I use #define x (6+3) the output is 9 81 729 6561

Upvotes: 0

Views: 358

Answers (4)

KOUSIK MANDAL
KOUSIK MANDAL

Reputation: 2052

This is a case of operator precedence. You can study about it a bit. I am describing on this matter as follow.

If you use

#define x 6+3

then

x = 6+3= 9

x*x = 6+3 * 6+3 = 6+18+3 = 27 (as * has higher precedence as operator than + ; so 3*6 will be evaluated earlier )

and similarly goes on.

Now if you use

#define x (6+3)

then

x = (6+3) = 9

x*x = (6+3)*(6+3) = 9*9 = 81

and similarly goes on.

So my suggestion is to use brackets always for better readability and understanding.

Upvotes: 2

Rafiwui
Rafiwui

Reputation: 554

#define simply replaces the character token (in your case x) with what you defined it to be. So your example would look like this after the preprocessor did his work:

#include<stdio.h>
#define x 6+3
int main(){

    int i;
    i=6+3;    //9
    printf("%d\n",i);
    i=6+3*6+3;  //27
    printf("%d\n",i);
    i=6+3*6+3*6+3;   //45
    printf("%d\n",i);
    i=6+3*6+3*6+3*6+3;    //63
    printf("%d\n",i);

    return 0;

}

And if you look over it you see why e.g. the second example is 27 instead of 81 (* before +).

On the other hand if you write (6+3) it will be 9*9 and thats what you would expect it to be.

Upvotes: 5

mksteve
mksteve

Reputation: 13073

macro expansion is a text replacement. So

 #define x 6 + 3
 #define y (6+3)

Gives the following

 printf( "%d %d\n", x , y );        // 6 +3 , (6+3) is 9 and 9
 printf( "%d %d\n", x *x , y * y ); //  6 + 3 * 6 + 3,  (6+3) * (6+3)
                                    //  6 + 18 + 3   ,  9     *  9
                                    //       27      ,  81

Upvotes: 1

Gor Asatryan
Gor Asatryan

Reputation: 924

Name of macro is replaced by the contents. It means that

#define x 6+3
x*x*x*x = 6+3*6+3*6+3*6+3 = 6+18+18+18+3

when you define x as (6+3) - (6+3) inserted. It means that

#define x (6+3)
x*x*x*x = (6+3)*(6+3)*(6+3)*(6+3) = 9*9*9*9

Read about C Preprocessor and Macros

Upvotes: 1

Related Questions