2
#define CLog( s, ... ) NSLog( @"%@", [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#define PO(x) CLog(@#x ": %@", x)

Then I do:

 NSString * hello =[NSString stringWithFormat:@"%@, %@",theCatalogData.id,@(theCatalogData.images.count)];
    PO(hello);

Works

Of course, a shortened version of this is simply:

PO([NSString stringWithFormat:@"%@, %@",theCatalogData.id,@(theCatalogData.images.count)]);

That doesn't work. I wonder why.

No emergency. No problem. The longer equivalent works anyway. I just want to understand how the compiler parses the macro to see why things don't work.

user4234
  • 1,523
  • 1
  • 20
  • 37

1 Answers1

7

Since the pre-processor does not really understand syntax in itself, macro parameters containing commas will cause problems.

In the second case, since the parameter contains two commas outside of quotes, the compiler thinks the macro is getting 3 parameters instead of one, and since the macro takes only one parameter, the compiler will complain.

A simplified test case similar to your second case;

#define TEST(a,b,c) a
TEST([d e:@"%@, %@", f, g])

will expand to;

[d e:@"%@, %@"

which shows that the a parameter only contains all characters up to the first un-quoted comma.

In your case, you define the TEST macro to take one parameter and since the pre-processor considers it 3, compilation will fail.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
  • Awesome. How do you know what the macro will expand to? – user4234 Jan 01 '13 at 08:47
  • @SharenEayrs I just pasted the above sample into a file called `test.c` and ran `gcc -E test.c` from a console window ([requires that the command line tools are installed](http://stackoverflow.com/questions/10265742/how-to-install-make-and-gcc-on-a-mac)). It will output the pre-processed file to the console so you can visually inspect it. – Joachim Isaksson Jan 01 '13 at 08:53
  • Also of note, you can do what you want you just need to wrap your argument in another set of parenthesis. So something like `MACRO(([NSString stringWithFormat:@"%@-%@", foo, bar]))` would be fine. – axiixc Apr 22 '13 at 02:26