Checking the return value of a function in a macro
I have core function which I can call from the customized module of the product.
function_core
is the core function which will return and integer
we have a macro in header file:
#define func_cust function_core
I am calling
func_cust
inside my customized code.
But inside the core we again call some other core function:
#define function_core main_core
so I cannot put in my customized code all the arguments.
I am calling this func_cust
function call in many C files.
I need to check the return value of the function function_core
like
if function_core
returns x then I want to change the return value to 0 or else same return value will be returned.
For example I want to define a macro like 开发者_C百科this:
#define funct_cust ((function_core==x)?0:function_core)
Is this possible?
To be more specific this is what i need!!
#include<stdio.h>
#define sum_2 ((sum_1==11)?0:sum_1)
#define sum_1(a,b) sum(a,b)
int sum( int ,int);
int main()
{
int a,b,c;
a=5;
b=6;
c=sum_2(a,b);
printf("%d\n",c);
}
int sum(int x,int y)
{
return x+y;
}
this gives an error :
"test_fun.c", line 12.3: 1506-045 (S) Undeclared identifier sum_1.
I only have the access to play with this macro sum_2.
It's better to write an inline function (C99 supports this):
static const int x = ...;
static inline int funct_cust(void* args) {
int res = function_core(args);
if (res == x) return 0;
return res;
}
If you use gcc, you can use statement exprs:
#define funct_cust(args) ({ int res = function_core(args); res == x ? 0 : res; })
If you can add an actual function, it would be pretty easy:
int sanitize(int value, int x)
{
return (value == x) ? 0 : value;
}
Then just change your macro into
#define func_cust sanitize(func_core(), x)
This solves the otherwise hairy problem of not evaluating the function call twice, and not having to introduce a temporary (which is hard to do in a macro).
If evaluating twice is okay, then of course just do it like you outlined:
#define func_cust func_core() == x ? 0 : func_core()
Change it to (assuming a,b is constant)
#define sum_2(a,b) ({(sum_1(a,b)==11)?0:sum_1(a,b);})
#define sum_1 sum
int sum(int ,int);
This is not safe because a,b
can be non constant expressions too. So you may want to create local variables holding the value of a,b so they are only evaluated once (improved)
#define sum_2(a,b) ({ \
typeof(a) _a = (a); \
typeof(b) _b = (b); \
sum_1(_a, _b) == 11 ? 0 : sum_1(_a,_b); \
})
#define sum_1 sum
int sum(int ,int);
Do not miss any of the curly braces, semi-colon in the last statement, and the slashes.
精彩评论