Loading lessons...
Statements and Program Structure
Statements and Program Structure
Everything a C++ program shows you is a sequence of statements strung together. Let's see how they stack up.
What is a statement?
A statement is the smallest unit of work in a program: a single instruction. In C++ a statement ends with a semicolon.
int x; // a declaration (creates a variable)
x = 5; // an assignment (stores a value)
cout << x; // an output statement
int x;declares a variable.x = 5;stores the value 5 in it.cout << x;sends the value to the console.
Three statements, three tasks. Each one is a complete instruction.
A program is a list of statements
When main runs, it sweeps through its statements top to bottom. Order matters:
#include <iostream>
using namespace std;
int main() {
cout << "First!" << endl;
cout << "Second!" << endl;
return 0;
}
The console prints "First!" before "Second!", exactly because the statements run in order.
Structure: functions group statements
A function is a named bundle of statements. main is the function that's automatically called first. Real programs then create other functions to bundle repeating tasks.
Blocks
{ } - a block groups one or more statements into a unit. It tells the compiler "these lines belong together".
TL;DR
- A statement is a single instruction, usually ending with
;. - A program is basically a list of statements run in order.
mainis the starter function; other functions group tasks.{ }blocks bundle statements together.