Sandeep M Nath
Sandeep M Nath

Reputation: 9

Macros behaving differently in C and gives different output

Iam new to c. Here defined a macro as #define val 4+2. when try to print square using val*val it gives output as 14 instead of 36. How is this happening, but when macro is defined as #define val 6 it gives correct output. Here is the sample code snippet. Can someone explain why is this so?

#define max 4+2

int main()
{
   printf("%d\n",max);    
   int i = max*max;
   printf("%d\n",i);
}

output: 6 14

Upvotes: 1

Views: 93

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134316

After running your code through pre-processor (gcc -E)

//removing the content from stdio.h for brevity...

int main()
{
   printf("%d\n",4+2);   // output : 6, as expected
   int i = 4+2*4+2;      // note the expansion here, not what you'd expect!
   printf("%d\n",i);     // value of 'i' is not what you'd expect!
}

So, to elaborate a statement like

 int i = 4+2*4+2;

is effectively the same as

int i = (4) + (2*4) + (2) ;

which produces the output of 14, not 36, as for the lack of parenthesis-enforced operator precedence, default precedence is at work and it's executed as shown above.

Suggestion: Always wrap your macros in parenthesis to avoid this.

Upvotes: 0

Mureinik
Mureinik

Reputation: 311188

Macros are "stupid" text replacement, with no semantic understanding. If you replace "max" with "4+2" (which is what the preprocessor does), you'll see the initialization of i is resolved as:

int i = 4+2*4+2;

From here, it's easier to see that the result is 4+2*4+2=4+8+2=14.

If you want max to represent 6 "the hard way", you could surround it with parentheses:

#define max (4+2)

This way, the preprocessor will resolve:

int i = (4+2)*(4+2);

And you'll get i=36 as you expected.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409166

The statement

int i = max*max;

expands to

int i = 4 + 2 * 4 + 2;

which is equivalent to

int i = 4 + (2 * 4) + 2;

If you want the result to be

int i = (4 + 2) * (4 + 2);

then you need to explicitly add the parentheses in the macro:

#define max (4+2)

This is a common "flaw" with macros, and one reason their usage is discouraged, or to be used for very simple constant values only.

Upvotes: 2

Related Questions