C++ Syntax
Learning the basic rules and structure of C++
📝 C++ Syntax Rules
C++ syntax defines the rules for writing valid C++ code. Understanding these fundamental rules is essential for writing programs that compile and run correctly without errors.
// Basic C++ syntax example
#include <iostream>
using namespace std;
int main() {
cout << "Learning C++ syntax!" << endl;
return 0;
}
Output:
Learning C++ syntax!
Essential Syntax Elements
Semicolons
End every statement with semicolon
cout << "Hello";
Braces
Group statements into blocks
if (true) {
// code block
}
Case Sensitive
Uppercase and lowercase matter
int Age; // different from
int age; // this variable
Preprocessor
Directives start with #
#include <iostream>
🔹 Program Structure
Every C++ program has a defined structure: includes, possibly a namespace, functions (especially
main()), and statements. It starts with preprocessing directives like
#include <iostream>. The main() function is the entry point where execution begins.
Code is organized into functions for modularity. Statements end with semicolons. Understanding this structure is
foundational—it ensures proper compilation and linking. Larger programs split code across multiple files (headers
and source files) for maintainability.
// 1. Preprocessor directives
#include <iostream>
#include <string>
// 2. Using declarations (optional)
using namespace std;
// 3. Function declarations (if needed)
void greetUser();
// 4. Main function (required)
int main() {
// Program execution starts here
cout << "Program structure example" << endl;
greetUser(); // Call our function
return 0; // End program successfully
}
// 5. Function definitions
void greetUser() {
cout << "Hello from a function!" << endl;
}
Output:
Program structure example
Hello from a function!
🔹 Variables and Data Types
Variables are named memory locations used to store and manipulate data, and their behavior is defined by
their associated data type. Declaring a variable (e.g., int age;) allocates memory and
specifies what kind of data it will hold. Initialization assigns an initial value at the point of declaration. The
choice of data type (like char for a grade or int for an age) dictates the operations that
can be performed and the memory used. Proper variable naming and type selection are cornerstones of writing clear,
efficient, and maintainable code.
#include <iostream>
#include <string>
using namespace std;
int main() {
// Integer variables
int age = 25;
int year = 2024;
// Floating-point variables
double price = 19.99;
float temperature = 36.5f;
// Character and string variables
char grade = 'A';
string name = "John Doe";
// Boolean variable
bool isStudent = true;
// Display all variables
cout << "Name: " << name << endl;
cout << "Age: " << age << " years" << endl;
cout << "Grade: " << grade << endl;
cout << "Price: $" << price << endl;
cout << "Is student: " << isStudent << endl;
return 0;
}
Output:
Name: John Doe
Age: 25 years
Grade: A
Price: $19.99
Is student: 1
🔹 Operators and Expressions
Operators perform actions on operands: arithmetic (+, -, *,
/, %), relational (==, !=, <,
>), logical (&&, ||, !), and more.
Expressions combine variables, literals, and operators to produce a value. Understanding operator precedence and
associativity is key to writing correct expressions without excessive parentheses. Special operators include
assignment (=), compound assignment (+=, -=), increment/decrement
(++, --), and the ternary conditional operator (? :) for concise if-else
choices.
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 3;
// Arithmetic operators
cout << "=== Arithmetic Operations ===" << endl;
cout << a << " + " << b << " = " << (a + b) << endl;
cout << a << " - " << b << " = " << (a - b) << endl;
cout << a << " * " << b << " = " << (a * b) << endl;
cout << a << " / " << b << " = " << (a / b) << endl;
cout << a << " % " << b << " = " << (a % b) << endl;
// Comparison operators
cout << "\n=== Comparisons ===" << endl;
cout << a << " > " << b << " is " << (a > b) << endl;
cout << a << " == " << b << " is " << (a == b) << endl;
return 0;
}
Output:
=== Arithmetic Operations ===
10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3
10 % 3 = 1
=== Comparisons ===
10 > 3 is 1
10 == 3 is 0
🔹 Control Structures
Control structures dictate the flow of execution: if, else, switch for
decisions; for, while, do-while for loops. if tests
a condition; loops repeat a block. The for loop is ideal when the number of iterations is known.
while checks the condition before each iteration; do-while checks after, ensuring the body
runs at least once. Control structures are fundamental to implementing algorithms and logic. Nesting them allows
complex behaviors, but strive for clarity to avoid "spaghetti code."
#include <iostream>
using namespace std;
int main() {
int number = 15;
// If-else statement
if (number > 10) {
cout << number << " is greater than 10" << endl;
} else {
cout << number << " is not greater than 10" << endl;
}
// For loop
cout << "Counting from 1 to 5: ";
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << endl;
// While loop
cout << "Countdown: ";
int count = 3;
while (count > 0) {
cout << count << " ";
count--;
}
cout << "Go!" << endl;
return 0;
}
Output:
15 is greater than 10
Counting from 1 to 5: 1 2 3 4 5
Countdown: 3 2 1 Go!
🔹 Common Syntax Errors
Common C++ syntax errors include missing semicolons, mismatched braces, undefined variables, and type
mismatches. Forgetting to close a string literal or comment can cause cascading errors. Using
= instead of == in conditions is a frequent logical error. Include the correct headers for
libraries like <iostream> or <vector>. Compiler error messages help locate
issues—read them carefully, starting from the first reported error, as later errors may be consequences of earlier
ones. Using an IDE with syntax highlighting reduces these mistakes.
Syntax Error Examples:
- Missing semicolon:
cout << "Hello"❌ →cout << "Hello";✅ - Missing braces:
if (x > 0) cout << x❌ →if (x > 0) { cout << x; }✅ - Wrong case:
Cout << "Hi";❌ →cout << "Hi";✅ - Missing return:
int main() { }❌ →int main() { return 0; }✅