Reputation: 1031
I need to create a macro
DISP(sqrt, 3.0)
that expands into
printf("sqrt(%g) = %g\n", 3.0, sqrt(3.0));
Here is my current attempt that doesn't quite work yet:
#include <math.h>
#include <stdio.h>
#define DISP(f,x) printf(#f(%g) = %g\n", x, f(x))
int main(void)
{
DISP(sqrt, 3.0);
return 0;
}
gcc -E
shows that I currently have an extra double quote in there.
If I put any double quotes or escaped double quotes before my #f or if I use ##f the macro no longer expands. How to fix?
Upvotes: 2
Views: 4254
Reputation: 13590
You can use this:
#define DISP(f,x) printf(#f "(%g) = %g\n", x, f(x))
this expands to
printf("sqrt" "(%g) = %g\n", 3.0, sqrt(3.0));
In C you can combine two or more string literals into one like this:
const char *txt = "one" " and" " two";
puts(txt);
which will output one and two
.
edit
Also note that it is recommended to put the macro and the macro arguments inside parenthesis:
#define DISP(f,x) (printf(#f "(%g) = %g\n", (x), (f)(x)))
Upvotes: 4
Reputation: 296
You want this:
#define DISP(f,x) printf(#f"(%g) = %g\n", x, f(x))
that provides the following output:
sqrt(3) = 1.73205
(See http://codepad.org/hX96Leta)
Upvotes: 6