-2

When i compile the following program I get the output as 47. I expected the output to be 144

#include<stdio.h>
#define FIRST_PART 7
#define LAST_PART 5
#define ALL_PARTS FIRST_PART + LAST_PART
int main() {
printf ("The Square of all parts is %d", ALL_PARTS * ALL_PARTS) ;
return(0);
}
user3762146
  • 205
  • 3
  • 13

7 Answers7

1

The preprocessor works before the compiler. It is a simple 'stupid' text-replace mechanism. Therefore:

  • ALL_PARTS gets converted to 7 + 5

  • ALL_PARTS * ALL_PARTS gets converted to 7 + 5 * 7 + 5.

Because of this mechanism, it is recommended to surround the parameters of macros with parentheses and also surround the whole macro with parentheses, such as:

#define ALL_PARTS (FIRST_PART + LAST_PART)

Mark Segal
  • 5,427
  • 4
  • 31
  • 69
1

FIRST_PART + LAST_PART will evaluate as 7 + 5 (It's no more than a text substitution).

You expression is then 7 + 5 * 7 + 5 which is 7 + 35 + 5 (as multiplication has a higher precedence than addition). The value of 7 + 35 + 5 is, of course, 47.

A remedy is to use (FIRST_PART + LAST_PART) as your definition.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0
ALL_PARTS * ALL_PARTS

Will become

FIRST_PART + LAST_PART * FIRST_PART + LAST_PART

Which is

7 + 5 * 7 + 5 = 7 + 35 + 5 = 47

So 47 is the expected answer.

If you want to see your expected result, you need to add () to your define

#define ALL_PARTS (FIRST_PART + LAST_PART)
Alex Lop.
  • 6,810
  • 1
  • 26
  • 45
0

Your Preprocessor evaluated as

printf ("The Square of all parts is %d", ALL_PARTS * ALL_PARTS) ;

then

printf ("The Square of all parts is %d", FIRST_PART + LAST_PART * FIRST_PART + LAST_PART) ;

and then

printf ("The Square of all parts is %d", 7 + 5 * 7 + 5) ;

So your final result is 47

To get desired result you can use

#define ALL_PARTS (FIRST_PART + LAST_PART)
ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42
0

Just need to change this:

#define ALL_PARTS FIRST_PART + LAST_PART

To this:

#define ALL_PARTS (FIRST_PART + LAST_PAR)
Hayden
  • 2,902
  • 2
  • 15
  • 29
0

FIRST_PART is 7 LAST_PART is 5

FIRST_PART + LAST_PART is 7 + 5

7 + 5 * 7 + 5 = 7 + 35 + 5 = 47

To fix, do

#define ALL_PARTS ( FIRST_PART + LAST_PART )
Magisch
  • 7,312
  • 9
  • 36
  • 52
0

Your code is expanded to 7+5*7+5 = 7+35+5 = 47. This is a very common failure.

johnjohnlys
  • 394
  • 1
  • 9