Team 2550
Technical Documentation
 All Files Variables Pages
Program Layout

All C++ programs have a basic layout that does not really change. Even programs as trivial as "hello world" have a basic layout.

#include <iostream>
using namespace std;
int main()
{
cout << "hello world";
//cout was allowed because I included the iostream library, the <> tells
//the preprocessor to look in the default system path for that library
//cout is the equivalent of the print command in many other languages
}

You will probably almost immediately notice the int main() line below the heading. In C++ and C, main defines any code that runs by default without being "called." In other words, you can and will have other code below the exit of main(), but that code will not run unless it is referenced in main(). Another thing to note is the () after main. These parenthesis tell the computer that main is a function. Again, I will cover functions in-depth later. Right now, all you need to know is that main() is a function built into C++ that runs automatically.

Note
I would encourage you to copy and paste some of the code I have put before this section into an IDE (such as MS Visual Studio or Code::Blocks) and run it in main(). If you try just pasting the code without main(), it will likely give you errors. Go ahead and try both.

main() is the default function to run for many strains of C++, however, you do not always use main(). For instance, Arduino (a simple programmable microcontroller) has two functions that run by default. This structure is shown below...

//heading goes here
void setup()
{
//configure inputs and outputs
//this is code that only need to run once
}
void loop()
{
//this code repeats infinitely, and is usually the body of your program
}

The code used by FIRST robotics is laid out similar to that of Arduino. However, the FIRST robotics code is slightly more complex. We will cover FIRST-specific programming in a later manual.

Right now, all you need to know is that typical C++ programs have three components.

//header
//put files to include and preliminary instructions here,
//including constant definitions
int main() //the code in main() runs right after the preliminary instructions are run
{
//insert code to run here
}
//more functions go down here
//they are only run if you "call" them from main() directly or indirectly

You may have noticed that main() has a type (int in this case). All a function does is return an output based on its input(s), this is the type of value the function will return after running. By default, main() returns a value of 0, meaning the the program exited without errors (it is reasonable to assume this is where many "error codes" come from).

The default return value for main() is 0, which tells the operating system that the program ran and exited with no errors.