News for hackers. Stuff that matters.
Re:C Macro Tips and Tricks by Xuzz on Friday December 31, 2010 @10:34PM (#2057152)
Great article, although I'd prefer if there was a bit less of a focus on Objective-C and Cocoa, since all the rest applies pretty much the same to plain C.

(However, that technique with blocks looks like a good solution to the "many statement expression in macro expression" problem, would that work with C++0x lambdas?)

Re:C Macro Tips and Tricks by bmastenbrook on Saturday January 01, 2011 @01:09AM (#2057303)
Yes, it'd work with 0x lambdas; however, the situations where this occurs in C are much less common in C++. Consider the "max" example given, as written in C++:

template <typename T> T max(T a, T b) { return (a > b) ? a : b; }

int max_ints(int a, int b) { return max(a, b); }

Of course this only works if "a" and "b" have the same type. 0x provides a solution for the situation where they don't:

template <typename Ta, typename Tb> auto max(Ta a, Tb b) -> decltype((a > b) ? a : b) { return (a > b) ? a : b; }

int max_int_char(int a, char b) { return max(a, b); }

Re:C Macro Tips and Tricks by Xuzz on Saturday January 01, 2011 @01:52AM (#2057331)
My question was more of if you have multiple statements, instead of a single expression, you wanted to stick inside a macro and preserve the ability to call it within another expression.

For example:

  #define SOMEMACRO(x) do { \
     int y=0;               \
     for(int i=0; i<x; i++) \
       y=dosomething(y, i); \
  } while (0)
Which, of course, works fine if you call it as a statement. But it doesn't work if you want to somehow "return" the value of "y" from that: there's no way to embed that kind of loop into an expression.

He showed an example of using Apple's Blocks to solve that, can you do the same with C++0x lambdas?

Re:C Macro Tips and Tricks by bmastenbrook on Saturday January 01, 2011 @10:47AM (#2057740)
As I said, 0x lambdas can do that...

... but you probably shouldn't: don't use a macro where a function will suffice, and if you need to use a macro, write a macro that syntactically wraps around a function if possible. C++, especially 0x, provides a lot of metaprogramming functionality you can use to avoid writing macros in many cases. Using this functionality will give the compiler more information about your program for analysis purposes, which means the compiler can help ensure correctness and better efficiency.

Re:C Macro Tips and Tricks by nitrogen on Saturday January 01, 2011 @07:10AM (#2057546)
Gcc can do some interesting things with macros. I have used multi-statement macros that "return" a value. Another option is using the comma operator, which I think is legitimate C.
Re:C Macro Tips and Tricks by paxswill on Saturday January 01, 2011 @04:10AM (#2057414)
To give some context, most of the content of the blog deals with some of the edges of Obj-C and Cocoa, such as defining classes at runtime and other generally weird things.