1

Hi, I tried to define something comparable to a little function, even though it doesn't output any error the result is: 0.00000000

#include <stdio.h>

#define LOGIC(X,Y){\
            if(X>Y)\
                printf("%lf",X);\
            else\
                printf("%lf",Y);\
}

int main(){

    LOGIC(4,3);
    return 0;
}

Why is so and how to make it work?

jxh
  • 69,070
  • 8
  • 110
  • 193
  • 1
    Wrong format specifier is at least one issue. You can replace `printf("%lf",X);` with `printf("%lf",(double)(X));` Apart from that, use `do { } while (0)` instead of plain braces and put parentheses around the parameters. These extra things aren't the cause of your issue but they generally make macros safer to use and are generally a good idea. – mediocrevegetable1 Aug 29 '21 at 10:34
  • 1
    Turn on more compiler warnings. You are passing an `int` parameter to `printf`, but telling `printf` it is a `double`. – jxh Aug 29 '21 at 10:34
  • If you're using a macro as a simple function, you should probably just use a function instead. – interjay Aug 29 '21 at 10:37
  • thx, didn't now I had to cast the type, I putted 'double' format specifier for, being sure it would fit I guess(it was a stupid idea)? but can I enter any argument on a #define @jxh – XxCharbonChainsxX Aug 29 '21 at 10:41
  • && @mediocrevegetable1 – XxCharbonChainsxX Aug 29 '21 at 10:44
  • @XxCharbonChainsxX your macro arguments should be expressions of any type that is convertible to double. – mediocrevegetable1 Aug 29 '21 at 10:47

1 Answers1

4

First, you should have a very good reason to choose a macro like function over an actual function. If you had used a function, you would be able to specify that the function parameters should be double more naturally.

void logic (double x, double y) {
    if (x > y) {
        printf("%lf\n", x);
    } else {
        printf("%lf\n", y);
    }
}

Since you are using a macro, there is no type specified for the arguments. So, if you pass in an int argument to the macro, that is how it is treated in the expansion. Undefined behavior results when printf is told to expect a double parameter when an int was passed in instead.

One way to fix the macro is to assign the parameters to local variables with the appropriate type, which better emulates what an actual function would do.

#define LOGIC(X,Y) do {\
        double XX = (X); \
        double YY = (Y); \
        if(XX>YY)\
            printf("%lf",XX);\
        else\
            printf("%lf",YY);\
} while (0)
jxh
  • 69,070
  • 8
  • 110
  • 193