Computing using float in macros in C

My colleague and I are learning from a test where we need to analyze the C code. Looking through the tests of past years, we saw the following code, which we really do not 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?

Thank you very much in advance!

+4
source share
2 answers

Compiler warnings ( format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’) provide more than enough information. You have to fix yours format-specifier, which should be %lfinstead %d, as you are trying to print the value double.

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

printf , , . , float int. -, , . 0.

+3

  • (%f)

#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;
}

The average is 4.500000

, 7.500000 - .

, , int.

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

The average is 4
0

Source: https://habr.com/ru/post/1662229/


All Articles