A statement: Statements in C++


What is a statement?

In the simple code in the previous blog about C++ we entered the following code:

// A first C++ program
// The slashes are required a the beginning of each line

/* This is also a comment
  with a second line */

 

#include <iostream>

int main()
{
    std::cout << "Game Over!" << std::endl;
    std::cin;
    system("pause");

    return 0;
}

Discussion about the code

Header File

The following is not a statement, it is a preprocessor directive, this is indicated by the # or pound symbol at the beginning of the line.  The preprocessor runs before the compiler compiles the code into machine language for use by the computer.  The word include orders the preprocessor to include the contents of another file.  The file iostream is part of the standard library that gives you the ability to do input and output to the screen.  The < and > symbols tell the preprocessor to look where it stores the rest of the files that came with the C++ program (not your program).

#include <iostream>

main()

The next line is also not a statement, it is the header of a function called main()

int main()

Finally beginning of a function

Beginning of the function: {

Last line of the program (in this case the function): }

Between the braces (sometimes called curly braces) is part of the function and is referred to as a block, the code is indented and is called the body of a function.

Displaying the text

std::

MM900284095[1]Using the boring console approach, we output the code using the std or standard namespace.

The double colon is used to prefix the namespace, which seems odd since the :: comes after the namespace, which would make it a postfix if you think about it.  The compiler doesn’t think like you do.

 

cout

cout is an object that iostream defines and is used to send data to the standard output stream.  Keep in mind that the output could be your video on your laptop, it could be the flatscreen connected to your Xbox, it could be a watch display, and so forth.  It does not have to be things you normally use in computer science.

cin

cin is normally used to get an input from the computer user, but in this program it isn’t used for anything in this program.

endl

endl similar to pressing Enter key anything following will be in a subsequent line not on the same line.

Statements end with a semi-colon

Completed statements end with a semi-colon, more on this later.

return 0;

return 0 indicates the return doesn’t return anything, the zero actually mean nothing.

system(“pause”)

This pauses the program so that you can see the output.

Comments (1)