Dim Ka Dim Ka - 1 year ago 83
C++ Question

C++ "Compiler" with preprocessor

So we have an assignment in which we create something like a compiler for a pseudo language.


... //code
VAR(name) = NUMBER(2.3)

We have to handle this with the preprocessor and turn it into c++ code.


#define PROGRAM_BEGIN int main(){
#define PROGRAM_END return 1;}

What I have trouble with is that we have to support code like:

VAR(name) = NUMBER(1)+NUMBER(2.5)

After much thought I had a couple of ideas but nothing has worked so far (for example, use variables with dynamically created names). I guess that with some proper data handling, I've already made plans to organize the input into classes and use of the operator overload could help make this work but I still can't see the big picture.

Answer Source

Try this (the cout is for debug only):

#include <iostream>
using namespace std;

#define PROGRAM_BEGIN   int main(){
#define PROGRAM_END     return 1;}
#define VAR(x)          auto x
#define NUMBER(x)       x

VAR(name) = NUMBER(1) + NUMBER(2.5);
cout << name << endl;

By using auto you don't need to worry if VAR is an int or float.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download