KoblentsBlog Photography
Contact About
Ches
How do I make a C++ macro behave like a function?
I had seen this code before, and never understood why it was written the way it was. Now I do! Here's the background:
A macro acting like a function should allow this to work as expected:
123
if (cond)
	FUNC(x, y);
do_stuff();

As well as:
12345
if (cond)
	FUNC(x, y);
else
	FUNC(y, x);
do_stuff();

But not:
123
do_stuff();
FUNC(x, y)	// note no semicolon
do_stuff();

If you write a naive function as a set of commands, you violate all of the expectations.
123
#define FUNC(x, y)		\
	print x;		\
	print y;		\

Of course, you can introduce braces for scope:
12345
#define FUNC(x, y)		\
{				\
	print x;		\
	print y;		\
}

But now the third is still violated - no semicolon yet it still works. Here's an interesting bit of code that I finally understand, that solves all three problems:
12345
#define FUNC(x, y)		\
do {				\
	print x;		\
	print y;		\
} while (0)
Reference: StackOverflow
Ches Koblents
November 20, 2014
 
« Newer Older »
© Copyright Koblents.com, 2012-2017