A C++ program's execution begins with a function named main. This function serves as the entry point for the application.
int main()
{
// Program logic is placed here.
}
The keyword int specifies the function's return type. A function consists of four primary components: the return type, the function name, a parameter list enclosed in parentheses, and the function body enclosed in braces {}.
While main is not a reserved keyword in the language, the compiler and runtime environment require its presence for a program to be executable.
An empty parameter list, as shown above, indicates the function accepts no arguments. Functions can also be defined to receive parameters.
int main(int firstValue, int secondValue)
{
// Code that uses firstValue and secondValue.
}
Comments, which are ignored by the compiler, can be added using double slashes //.
Classes are user-defined types that allow for data abstraction. Their definitions are typically separated into a header file, which declares the class interface, and a source file containing the implementation.
To perform input and output operations, the standard iostream library is used. Its functionality must be made available by including the appropriate header.
#include <iostream>
The predefined cout object, coupled with the output operator <<, is used to write data to the standard output stream.
std::cout << "Enter your name: ";
This line is a sattement, the fundamental unit of execution in C++, terminated by a semicolon.
To store user input, an object of a suitable type must be declared. For textual data, the standard string class is appropriate.
std::string userName;
This is a declaration statement. To use the string class, its header must also be included.
#include <string>
User input is read from the standard input stream cin using the input operator >>.
std::cin >> userName;
To move the output cursor to a new line, the newline character constant '\n' can be sent to cout. Character literals are ecnlosed in single quotes.
std::cout << '\n';