# Converting C++ macros to C#

This topic is 4977 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am in the process of converting a program made in C++ to C# and .NET. This, however, includes some C++ macros that I do not know how to deal with. Would C++ macros be converted into C# functions, or what is the best bet? I want to eliminate the macros but keep their functionality. Here they are:
#define ASSERT_STACK_ELEMENTS(x) if (stackPointer < x) { error = STACK_VIOLATION; break; }

#define ASSERT_STACK_NOT_FULL if (stackPointer == STACK_DEPTH) { error = STACK_VIOLATION; break; }

#define PUSH(x) (stack[stackPointer++] = x)
#define POP (stack[--stackPointer])
#define PEEK (stack[stackPointer-1])

First off, I'd love to know what these macros mean. I am familiar with C++, but I never got into macros. What is the point of them, over something.. else? How do these macros work? Secondly, how can I convert these macros into solid C# code? I am guessing I would need their function equivalent, but I do not know it. Any help or ideas? Thank you much.

##### Share on other sites
They look like they were part of a badly written virtual machine.

I don't know C#, but macros in C++ substitute text. If you to write PUSH(5) in your program, the preprocessor would replace it with (stack[stackPointer++]=5) and then the result would get compiled.

##### Share on other sites
The macros looks like some kind of array-based stack, with
the array (named "stack") probably a global variable.

I'd imagine that you can just use the System.Collections.Stack
to replace those macros... by using a proper stack class.

##### Share on other sites
Quote:
 Original post by smart_idiotI don't know C#, but macros in C++ substitute text. If you to write PUSH(5) in your program, the preprocessor would replace it with (stack[stackPointer++]=5) and then the result would get compiled.

Like this:
int main(){   PUSH(5);   return 0;}

Becomes:
int main(){   (stack[stackPointer++] = 5);   return 0;}

You can also create a function to replace the macro:
void AssertStackElements( int x ){   if ( stackPointer < x )   {      error = STACK_VIOLATION;      break;   }}

Those macros are bad macros though. stackPointer, STACK_VIOLATION, and error are undeclared; and a break in an if statement!?
So you pretty much have to rewrite the code.

PS:
I'm loving this new source tag, it's small and doesn't take up much space as it used to. but lol, only in Mozilla. It's still a big huge box in IE.

##### Share on other sites
As just a quick port I'd write functions for them, and with the ASSERT... functions throw an exception that gets caught where ever the break would have taken the execution flow.