Basic Program Structure - itzjac/cpplearning GitHub Wiki

Every program contains

Any C++ program should contain one or more functions, one of which must be named main. The operating system runs a C++ program by calling main.

Every time a functions is contained in a program, we use the term define a function always containing four elements: a return type, a function name, a possibly empty parameter list, and a function body.

The return value of a program

On Unix-like systems we obtain the status after executing the program, by writing

$echo $?

On Windows systems

$echo %ERRORLEVEL%

Comments

Basic Input/Output

Streams

cout cerr cin clog

Redirecting streams

#include 

int main()
{
	int a, b, c, d;
	std::cout<<"Write 4 ages"<	std::cin >> a;
	std::cin >> b;
	std::cin >> c;
	std::cin >> d;
	float average = (a + b + c+ d)/4.f;
	std::cout<<"The average of the ages " << a << "," << b<<", ";
	std::cout<< c << "," << d<<" is: "<
	return 0;
}

Every time the program is run, ages are expected to be written at the command prompt.

This task is very repetitive and error prone. Taking advantage of the OS features, we can redirect the input so that our input values are read from a text file (one that we can create, store and modify permanently), for that we can run the program as follows

$average < ages.txt

The file will contain a list of ages separated by any type of blank space: tabs, space or carry returns.

ages.txt

44 80 12 5

EXERCISE: Now consider names of persons instead of ages. Declare appropriate variable to store this data.

Either use one word names or full name in Camel-case notation (or any other notation that promotes readability)

CHALLENGE: If full names are provided one per line, containing spaces. How could you process the names using std::cin?

Indentation and formatting

Curly brackets

Number of spaces for a tab

Improve readability, you are going to code with a team

Consistency!

Code Blocks and variables scope

TODO

Shadowing a variable

TODO

⚠️ **GitHub.com Fallback** ⚠️