1
votes

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?

2
Of course the " don't match. There is only one in the code - see answer.Weather Vane

2 Answers

6
votes

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)

4
votes

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)))