'Is this the defined behavior?
I have made a macro:
#define QUEUE_SEND_STATUS(x) ( (x == 0) ? printf("Fail\n") : printf("Success\n"))
It works as expected. But, my question is is that is this behavior defined in C? Can function calls be used in MACROS?
Thanks!
Solution 1:[1]
Yes, this code has well-defined behavior. However, there are some ways it could be improved.
Function-like macro parameters should be surrounded by parenthesis whenever used, to prevent operator precedence bugs:
((x) == 0). (The check vs zero is actually superfluous, you could as well just type(x) ?)You can use the printf calls inside the
?:operator only because they have the same/compatible return types. In case they were different functions with different return types, it wouldn't be possible.The whole thing could be rewritten as:
#define QUEUE_SEND_STATUS(x) puts((x) ? "Fail" : "Success").
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lundin |
