You should use the :w command often to save your file when you are working on it. This will help protect you in the event of a system failure. This method will also allow you to save code in one window before compiling the file in another window. If there is an error, you can make changes and save with the :w command in the code window without having to quit vi repeatedly in order to compile. Then you can compile again in the other window.
Also, you will generally use :wq when you wish to end your vi session, saving all changes you made to the file.