9/11/2011

C/C++: Creating an alternative syntax

If you can't explain it simply, you don't understand it well enough.
Albert Einstein

Today, for the first time, I will be posting about something not related to TBS. I'll be showing you how to use macros in C or C++ to create an alternative syntax. This can be fun if you like inventing new syntaxes but you don't want to write a complex compiler or interpreter.

Actually, it's really simple. All we need is one header file that contains some macros. For example, I quickly wrote the following for this tutorial:
#include <iostream>
#include <string>
using namespace std;

#define SHOW cout
#define ME <<
#define DA <<
#define GIMME cin
#define UR >>

#define SAM3 const
#define UESLES void
#define INTAGER int
#define TXT string

#define MANE main

#define BTW (
#define THX )
#define NVM )

#define TY ;
#define K ;

#define BRB {
#define BAK }

#define EMPTY ""
#define NUL 0
#define NAWLIEN endl
#define IZ =

This was written in C++ and it also includes some STL files. I saved this as "syntax.h" and then wrote the following:
#include "syntax.h"
UESLES GR33T BTW TXT MESAEG THX BRB
SHOW ME MESAEG TY
SHOW ME "!" TY
SHOW ME NAWLIEN K
BAK

INTAGER MANE BTW NVM BRB
GR33T BTW "H3LO WORLD" THX TY
TXT N4ME IZ EMPTY TY
SHOW ME "WUTS UR N4ME? " TY
GIMME UR N4ME K
SHOW ME "W0W UR N4ME IZ " DA N4ME TY
SHOW ME NAWLIEN TY
BAK
That really is all it takes. The syntax I created looks similar to the LOLCODE syntax(but is not at all an exact copy). Make sure to comment if you have any questions or simply to show your own syntax.

No comments:

Post a Comment