-2

I am trying to compile the following (in MSVC):

#define TRAP   (errorCode = (errorCode != 0) ? errorCode :) 

int someFunction(int a) {
     printf("Called function with parameter %d\", a);
     return (a > 3);
}

int main(void) {
  int errorCode = 0;
  printf("Error code starts out as %d\n", errorCode);  // errorCode should be 0
  TRAP  someFunction(1);    
  printf("Error code is now %d\n", errorCode);  // errorCode should still be 0
  TRAP  someFunction(4);
  printf("Error code is now %d\n", errorCode);  // errorCode should be 1
  TRAP  someFunction(2);    
  printf("Error code is now %d\n", errorCode);  // errorCode should still be 1, someFunction should not be called.
  return 0;
}

However, I get a compiler error at the first line containing "TRAP"

error C2059: syntax error : ')'

My question is: why? As I understand it, the macro pre-processor just does a find-replace for all instances of "TRAP" and replaces it with the text of the macro between the outermost parentheses. Thus, after the macro does its work, I would expect the first TRAP line to read:

errorCode = (errorCode != 0) ? errorCode : someFunction(1);

which is valid C; indeed inserting this line directly into my code compiles fine. Is there some macro nuance that I'm missing here?

I apologize if this is a stupid question--I'm pretty new to macros and a bit confused.

user1004061
  • 103
  • 1
  • 9
  • 1
    BTW, you can see how a macro expands if you're not sure what's happening. See [here](http://stackoverflow.com/q/277258/212858) for MSVC. – Useless Sep 21 '15 at 16:56
  • @Useless. Thanks for letting me know. This trick will definitely help me in the future. – user1004061 Sep 21 '15 at 17:17

2 Answers2

3

To have TRAP work the way you want you'd want to define TRAP as

#define TRAP   (errorCode = (errorCode != 0) ? errorCode :

i.e. without the trailing ). You'd then need to supply the trailing right-paren when you use the macro, as in

TRAP someFunction(1));

which is a bit ugly. To make it look a bit "nicer" you could parameterize the definition, as in

#define TRAP(func)   (errorCode = (errorCode != 0) ? errorCode : (func))

and then invoke it as

TRAP(someFunction(1));

Best of luck.

1

It would work, but you've surrounded the macro's contents in parenthesis, so it expands to, for example (errorCode = (errorCode != 0) ? errorCode :) someFunction(1);

Remove the parenthesis surrounding the macro contents and it should work.

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85