puer123 puer123 - 11 days ago 5
C Question

Calculating with a float in macros in C

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!

Answer

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.