Comma Operator BASICs

15 09 2011

For some of us BASIC was the first programming language we learned. Not because it was pedagogically great, but because it was pretty much the only programming language that was easily available. It came preinstalled on the earliest PC’s as well as the other home computers of the 80’s: Commodores, Sinclairs, Ataris, and many others.

Here is an example of BASIC program:

10 PRINT “What is your name? “;
20 INPUT name$;
30 PRINT “How old are you? “;
40 INPUT age;
50 PRINT “Hello, “,name$,”! Next year you will be “,age+1,” years old.”;
60 END

But hey! This blog was supposed to be about C++, so let’s make that program compileable with a C++ compiler. To do that, we need to do a few things.

Overload comma operator

Original creators of C++ deliberately misused the >> and << operators to read data from an input stream, and to write data to an output stream. I will emulate both functionalities using , (comma) operator instead. It is possible to use a single comma operator to emulate both >> and << operators, because the type of the first argument will determine whether input or output is intended:

template <typename T>

inline istream &operator,( istream &s,T &data ) { return s >> data; }

template <typename T>

inline ostream &operator,( ostream &s,const T &data ) { return s << data; }

Define required BASIC keywords

The BASIC keywords END, INPUT and PRINT are not a part of C++ language, but they can be defined using the C++ preprocessor:

#define END exit(0);

#define INPUT cin,

#define PRINT cout,

Forget about line numbering

Modern BASIC language doesn’t need line numbers anyway.

Once again, here is the complete code for this article.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: