I'll come straight to the point. I'm trying to create a Recursive Descent Parser in C++ for a hobby project which involves creating my own minimalist programming language.
One thing that puzzles me, though, is a dilemma about global variables. Clearly recursive descent requires me to implement multiple functions for each grammar patterns, which recursively parse the entire code. However, in about all examples of the parser I saw on the internet, none of the functions take any parameters and don't even return anything.
That would, normally, indicate the need of using global variables. But I'm rather worried about using them, as it is generally considered a bad idea to use global variables.
So, all I wish to know is:
Would using global variables in this case be fine? Or is there a better alternative?
Considering the C implementation of a Recursive Descent Parser in Wikipedia contains a global variable to store the current token as well, should I go with that method?
Though I must also inform you the tokenstream class I implemented allows LL(k) look-ahead, so storing just the current token in a global variable might not be enough.
Sorry if this question was already asked before, but I'm in a serious dilemma and thus seriously require your help.
Thanks in advance.
My conclusion: I realized that there's multiple solutions to this problem, as described in the answers below. I heard both sides of the argument and came to the conclusion that making a Parser class would be the best option because that way not only will it be organized but I can also run multiple instances of the Parser at the same time.
Another option would be to pass the tokenstream or the current token as a parameter to the grammar functions and return a value from the functions as well, but I didn't choose that as it might make the code more complicated.
Just simply using global variables inside an unnamed namespace (for internal linking) would also work but the first two methods are much more organized.
This is what I understood from the argument and I explained my choice so that anyone who views this in the future can be helped.
I hope I was of help.
Thanks to everyone again