-2

I am new to C programming and I have difficulty to understand what following code does? What does '##' in macro mean, also I don't quite understand how in macro definitions we have for example f1, but without arguments.

My question is different because I also have multiple defines

#include <stdio.h>
int a=1, b=2;
#define M(a,b) a ## b(a)
#define a t(f1,t(f1,f2(b)))
#define b(x) t(f2,t(f2,f1(a)))
#define ab(x) a+b(b)
typedef int (*i2i)(int);
int f1(int x) { return (++x); }
int f2(int x) { return (--x); }
int t(i2i f,int x) {return(f(f(x)));}
int main()
{
 printf("%d\n%d", M(a,b), ab(5));
 return (0);
} 

1 Answers1

1

The double-octothorpe "##" is known as the token-pasting operator. Whatever is on either side of it will be concatenated to form a single string. It lets you combine an argument with a fixed string, or combine two arguments. For example:

#define ADD_UNDERLINE(x)  _ ## x ## _
ADD_UNDERLINE(foo) // generates: _foo_

In your case, you have:

#define M(a,b) a ## b(a)
M(foo,bar)   // generates: foobar(foo)

Regarding your question about f1: The macros use bare function names, but they're used as parameters to the function t. The first parameter of t is type i2i, which is defined (via typedef) as a pointer to a function. Using just the bare function name here is generally equivalent to a pointer to that function (note: this isn't standard and would be better written in the macro as "&f1").

bta
  • 43,959
  • 6
  • 69
  • 99
  • We also have x in define, but x doesnt show anywhere after argument section. Where have x gone? – user2085124 Mar 03 '16 at 00:31
  • Ok, never mind, I suppose x is there just to confuse reader, and it really doesn't get used in define at all. – user2085124 Mar 03 '16 at 00:41
  • 1
    @user2085124- The argument for a macro isn't necessarily *required* to be used in the macro's expansion. There's rarely a good reason to do this, though, because it's very confusing for the reader. The code sample you posted appears to be intentionally difficult to read. – bta Mar 03 '16 at 00:42
  • Yes, it is from competition for students. Anyway, thanks! – user2085124 Mar 03 '16 at 00:49