How to set program counter?

This is an archive of a topic from NESdev BBS, taken in mid-October 2019 before a server upgrade.
View original topic
How to set program counter?
by on (#176968)
I'm trying to make a back function in a system of menus so that if the player presses the B button, it will take them back to the title screen. Using a recursive function call seems to cause the screen to go black after a few iterations, so I wonder: is there a way I can set the program counter directly to accomplish this?
Re: How to set program counter?
by on (#176969)
So, the program counter is what the CPU does to keep track of what line of code it's on while it executes. To explicitly change the line of code being executed (program count), you would use a JMP instruction (or GOTO in C).
Re: How to set program counter?
by on (#176973)
You normally wouldn't want to simply set the program count (which is really accomplished with a JMP instruction), because that would result in instantaneous (and possibly glitchy) transitions. Usually you'd maintain a set of state variables indicating the current screen/mode/etc., and pressing the button would merely change a state variable. The game's update routine would detect the state change and proceed to end the current state, possibly doing a fade out or any other sorry of "out" animation, before transferring control (JMP) to the initialization of the other state, which ideally will have an "in" animation.
Re: How to set program counter?
by on (#176993)
What you want is called a "finite state machine", you can search that term if you want to find other descriptions. It is exactly what tokumaru described.