4

My colleague and I are studying for a test, where we have to analyze C Code. Looking through the tests from the previous years, we saw the following code, which we don't really understand:

#include <stdio.h>
#define SUM(a,b) a + b
#define HALF(a)  a / 2

int main(int argc, char *argv[])
{
  int big = 6;
  float small = 3.0;

  printf("The average is %d\n", HALF(SUM(big, small)));
  return 0;
}

This code prints 0, which we don't understand at all... Can you explain this to us?

Thanks so much in advance!

puer123
  • 43
  • 1
  • 4

2 Answers2

3

The compiler's warnings (format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’) give more-than-enough information. You need to correct your format-specifier, which should be %lf, instead of %d, since you are trying to print a double value.

  printf("The average is %lf\n", HALF(SUM(big, small)));

printf will treat the memory you point as however you tell it to. Here, it is treats the memory that represents the float as an int. Because the two are stored differently, you should get what is essentially a random number. It needs not be 0 always.

Jarvis
  • 8,331
  • 3
  • 26
  • 54
  • Thanks for the explanation! – puer123 Nov 29 '16 at 07:43
  • 1
    just `%f` is enough – phuclv Nov 29 '16 at 07:43
  • @Jarvis: patience is a virtue; people have to wait a while before they're allowed to accept any answer (15 minutes, I believe). And soliciting for accept votes like that after less than 10 minutes is really a little too impatient. After a couple of hours, maybe. Granted, the 'Thanks' message from a newcomer is a little worrying; you can always point them to the FAQs ([How do I ask questions here?](http://stackoverflow.com/help/how-to-ask) and [What do I do when someone answers my question?](http://stackoverflow.com/help/someone-answers)). – Jonathan Leffler Nov 29 '16 at 07:50
0

To get correct output

  1. Add parentheses in macro
  2. Use correct format specifier (%f)

Corrected Code

#include <stdio.h>

#define SUM(a, b) (a + b)
#define HALF(a)  a / 2

int main() {
    int big = 6;
    float small = 3.0;
    printf("The average is %f\n", HALF(SUM(big, small)));
    return 0;
}

Output

The average is 4.500000

If you don't add parentheses, output will be 7.500000 due to operator precedence.

In case you need integer output, cast to int before printing.

printf("The average is %d\n", (int)HALF(SUM(big, small)));

Output

The average is 4
Shreevardhan
  • 11,453
  • 3
  • 36
  • 47