puer123
puer123

Reputation: 43

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!

Upvotes: 4

Views: 5986

Answers (2)

Shreevardhan
Shreevardhan

Reputation: 12641

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

Upvotes: 0

Jarvis
Jarvis

Reputation: 8564

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.

Upvotes: 3

Related Questions