0

I've been playing around with macros. I saw an interesting post where I can structure my macro in a function like structure here. I've tried to implement one and here is what I currently have.

#define Max(X,Y) \
do { \
     auto var1 = x; \
     auto var2 = y;  \
     var1 > var2 ? var1 : var2; \
} while (0)

and in my main function

void main()
{
   int result = Max(10, 5)
}

but I'm getting all these errors,

error C2059: syntax error : 'do'
error C2143: syntax error : missing ';' before '{'

Not sure what I did wrong. I just copied the code from the hyperlink above and just modified the code. Any help would be greatly appreciated!

Community
  • 1
  • 1
dwnenr
  • 443
  • 1
  • 4
  • 15
  • Why bother with macros? Just stuff it in a function and let the compiler inline it. – Captain Obvlious Nov 10 '15 at 00:50
  • Macros are not functions, nor lambdas as you're apparently using them... – 3442 Nov 10 '15 at 00:51
  • @CaptainObvlious I removed the c++ tag, but I just wanted to play around and learn how macro can be used. – dwnenr Nov 10 '15 at 00:51
  • Oh and doing something like `result = Max(++i, x)` will make debugging really really fun. – Captain Obvlious Nov 10 '15 at 00:51
  • @KemyLand So is the code that I written, just wrong? – dwnenr Nov 10 '15 at 00:52
  • @CaptainObvlious I am aware that ++i will cause a bug since macro just replaces texts, I am not using this anywhere. I just want to play around with macros – dwnenr Nov 10 '15 at 00:53
  • There's nothing wrong with the macro. The problem is that, unlike a lot of other languages, C++ loop control blocks do not have a return value. This means you can't assign something to the result of a loop because there is no such result. – Chris Hayden Nov 10 '15 at 00:53
  • @ChrisHayden I dont follow, is the auto var1 and auto var2 causing the errors? – dwnenr Nov 10 '15 at 00:54
  • do { } while() doesn't return anything. And it has no value. You cannot assign it to variable. – Michael Nastenko Nov 10 '15 at 00:54
  • 2
    You're aware that macros are text replacement. Then you should see that the fault lies in the use. `int result = do {...} while (0);` is not valid. – chris Nov 10 '15 at 00:54
  • @chris OH. I see. Thanks, I was totally missing that part. – dwnenr Nov 10 '15 at 00:55
  • @CaptainObvlious That's the point of assigning the parameters to local variables, so you don't get multiple side effects. – Barmar Nov 10 '15 at 01:24

1 Answers1

2

Consider what the macro expands into:

int result = do {
     auto var1 = x;
     auto var2 = y;
     var1 > var2 ? var1 : var2;
} while (0);

That's not valid C++ because loops don't have return values in C++.

Oh, and I actually did notice a small problem with the macro. The parameter names are capitalized (X, Y) but used as lower-case (x, y). That will not work as expected. You have to use the same name in the macro body as you used for the macro parameters.

Chris Hayden
  • 1,104
  • 6
  • 6