What is a Statement?

A statement is an instruction that tells the computer to perform some action. In C++, statements are the building blocks of programs.

Types of Statements

These are the common ones we will encounter for now.

Expression Statements

Most common type - expressions followed by a semicolon:

x = 5;                    // Assignment statement
std::cout << x;           // Output statement
++x;                      // Increment statement
result = x + y;           // Mathematical expression
std::cout << "Hello!";    // String output
x *= 2;                   // Compound assignment

Declaration Statements

Create and name variables:

int x;              // Declares variable x
int y = 10;         // Declares and initializes y
double price;       // Declares a decimal number variable
char grade = 'A';   // Declares and initializes a character
bool isReady;       // Declares a boolean variable
string name = "John"; // Declares and initializes a string
💡 Note
These are more advanced just take note they exist, we will learn more about them later!

Compound Statements (Blocks)

Group multiple statements with braces:

{
    int x = 5;
    std::cout << x;
    x = x + 1;
    std::cout << "New value: " << x;
}

Null Statements

Empty statements that do nothing:

;  // This is a null statement - just a semicolon

Selection Statements (Conditionals)

Control flow statements that choose between different paths based on conditions:

if (age >= 18) {
    std::cout << "You can vote!" << std::endl;
}

These include if, else, switch, and the conditional operator ?:.

Iteration Statements (Loops)

Control flow statements that repeat code multiple times:

for (int i = 0; i < 5; ++i) {
    std::cout << "Count: " << i << std::endl;
}

These include for, while, do-while, and range-based for loops.

💡 Note
We'll learn more about control flow statements like if, while, and for in later lessons. For now, focus on mastering the basic statement types!

Statements in a program

This demonstrates where to use statements in a basic program:

#include <iostream>    // Preprocessor directive

int main() {          // Main function
    // Statements go here
    return 0;         // Return statement
}

Previously the statement we have written here was:

std::cout << "Hello, World!" << std::endl;

Summary

Statements are the fundamental building blocks of C++ programs. The basic types we've covered include:

  • Expression statements: Perform actions like assignments and function calls
  • Declaration statements: Create and initialize variables
  • Compound statements: Group multiple statements with braces {}
  • Null statements: Empty statements using just a semicolon ;

Remember: these basic statements need semicolons to end them. Program execution starts at main() and executes the code between { and } from top to bottom.