Dim Ka Dim Ka - 8 days ago 6
C++ Question

C++ "Compiler" with preprocessor

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

Example:

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


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

Example:

#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

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

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

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