Some very simple C++ code



Here are a few very simple programs that will make text appear on the screen.


The first is the shortest possible C++ program that you can write to display something. Be warned, it is not the best way to do it:



    #include <iostream>


    main()
    {
        std::cout << "Hello from C++";
    }



The first line tells your program that you will be displaying text on the screen using an output stream. It tells the compiler that your program will make use of some standard code that someone else has already written for us, called the  <iostream>  library.


Execution will begin with the function called "main". The  ( )  brackets indicate that this function does not need any data when it begins execution - it has everything that it needs to begin.


"cout" means channel-out. This is the official name for the screen.


The  <<  arrows are called output-redirectors. They direct your text to the screen so that it can be displayed. Imagine that the arrows show the text where to go.



Ideally, any program that you write will let Linux know whether or not it executed successfully without encountering any errors. We can tell your program to give Linux a simple number as an error-code upon completion. The program will give back an integer (whole-number) using "return":



    #include <iostream>

    int main()

    {
        std::cout << "Hello from C++";


        return 0;
    }


Returning an error code of  0  indicates to Linux that no errors were encountered... everything went well once your program finished execution.


To make the program a little easier to understand, we can tell the compiler to use a few simple abbreviations from the standard namespace:



    #include <iostream>

    using namespace std;

    int main()

    {
        cout << "Hello from C++";


        return 0;
    }


Finally, we can add a few comments to make the code easier to understand. Simple comments begin with  //  double-slash.



Here is the program again, but with a few explanatory comments added:


    #include <iostream>    // Make use of screen for output


    using namespace std;    // Use standard names for screen etc.


    int main()

    {
        cout << "Hello from C++";    // Display text on screen


        return 0;    // Give error-code zero back to Linux
    }