C++ Statements
Introduction to C++ Statements
Statements are the building blocks of a C++ program. Each statement represents an instruction for the computer to execute.
A solid understanding of statements is essential for writing correct and efficient C++ code.
Basic Statement Examples
Here are some simple C++ statements that perform basic operations:
#include <iostream>
int main() {
std::cout << "Hello World!";
std::cout << "Welcome to C++!";
return 0;
}
Hello World!Welcome to C++!
Statement Characteristics
Execution Order: Statements are executed sequentially from top to bottom unless control flow alters it.
Semicolons: Not every statement ends with a semicolon. Expression and declaration statements do. Compound statements (blocks {...}
), if
/for
/while
/switch
/try
themselves do not. A do { ... } while (cond);
statement does end with a semicolon. The null statement is just a single ;
.
Whitespace: Whitespace between tokens is mostly ignored, but it matters inside string/character literals and for the preprocessor.
Multiple Statements: Multiple statements can appear on one line, but this is discouraged for readability.
Kinds of Statements (Overview)
Kind | Example |
---|---|
Expression | x = y + 1; |
Declaration | int n = 0; |
Compound (block) | { int a = 0; ++a; } |
Selection | if (ok) doWork(); / switch (v) { ... } |
Iteration | for (int i=0;i |
Jump | return; , break; , continue; |
Exception handling | try { ... } catch (...) { ... } |
Null | ; |
Common Errors and Best Practices
A common beginner error is forgetting to place a semicolon at the end of an expression or declaration statement. This results in a compilation error.
Best practices for readable code:
- Put each statement on its own line
- Use consistent indentation (2–4 spaces typical)
- Add comments to clarify complex statements
- Group related statements together with blank lines
#include <iostream>
int main() {
std::cout << "This will cause an error" // Missing semicolon here
return 0;
}
error: expected ';' before 'return'
Pitfall: Accidental Null Statement
A stray semicolon can turn a control statement’s body into a null statement and detach the intended block.
#include <iostream>
int main() {
bool ok = false;
if (ok); // <-- null statement; the next block always runs
{
std::cout << "This prints regardless of ok\n";
}
}