Basic syntax of C++

Syntax refers to the set of rules that define how code must be written in a programming language.

Basic Structure of a C++ Program

#include <iostream>  // Preprocessor directive

int main() {         // Main function - entry point of the program
    std::cout << "Hello, world!" << std::endl; // Output statement
    return 0;        // Return 0 to indicate success
}

C++ Syntax Breakdown

Comments

Used to explain code:

// This is a single-line comment
/* This is a
multi-line comment */

Variables and Data Types

int age = 25;
float weight = 65.5;
char grade = 'A';
bool passed = true;
std::string name = "Alice"; // From header

Input & Output

include

using namespace std;

int main() {
int x;
cout << "Enter a number: "; cin >> x; // Input
cout << "You entered: " << x << endl; // Output
return 0;
}

Conditional Statements

if (x > 0) {
cout << "Positive";
} else if (x < 0) {
cout << "Negative";
} else {
cout << "Zero";
}

Loops

For Loop:

for (int i = 0; i < 5; i++) {
cout << i << " ";
}

While Loop:

int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}

Functions

int add(int a, int b) {
return a + b;
}
int main() {
cout << add(3, 4); // Output: 7
}

Classes and Objects (OOP)

class Car {
public:
string brand;
int year;
void honk() {
    cout << "Beep!\n";
}
};

int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.year = 2022;
myCar.honk();
}

Arrays and Vectors

int nums[3] = {1, 2, 3};

#include <vector>
std::vector v = {1, 2, 3};
v.push_back(4);

Pointers

int x = 10;
int* p = &x; // p points to x
cout << *p; // Dereference → prints 10

Header Files

You can split code into files:

// add.h
int add(int, int);
// add.cpp

#include "add.h"

int add(int a, int b) { return a + b; }