C++ Study Guide: Syntax, Variables, Types, and Operators

1. C++ Syntax Fundamentals

C++ syntax defines how programs are written. Mastery of syntax is essential for writing clean, efficient code.

1.1 Structure of a C++ Program

#include <iostream>

using namespace std;

int add(int a, int b);

int main() {
    int result = add(5, 3);
    cout << "Result: " << result << endl;
    return 0;
}

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

1.2 Comments

// Single-line comment
/* Multi-line
   comment */

1.3 Identifiers and Naming Rules

1.4 Keywords to Know

CategoryKeywords
Controlif, else, switch, case, break, continue
Loopfor, while, do
Functionreturn, void
Object-Orientedclass, struct, public, private, protected, virtual, override
Memorynew, delete
Othersconstexpr, const, static, extern, mutable, typename

2. Variables

2.1 Declaration & Initialization

int x = 5;
double pi = 3.1415;
char c = 'A';
bool flag = true;

// Modern C++ (C++11+) uniform initialization
int y{10};
double e{2.718};

2.2 Variable Scope

void foo() {
    static int count = 0;
    count++;
    cout << count << endl;
}

2.3 Constants

const int DAYS_IN_WEEK = 7;
constexpr double PI = 3.1415926535; // compile-time constant

3. Types

3.1 Primitive Types

TypeSize (typical)Example
int4 bytes42
short2 bytes32000
long8 bytes100000L
float4 bytes3.14f
double8 bytes3.14159
char1 byte'A'
bool1 bytetrue/false

3.2 Derived Types

int a = 10;
int* ptr = &a; // pointer
int& ref = a;  // reference
int arr[5] = {1,2,3,4,5};

3.3 User-defined Types

struct Point {
    int x, y;
};

class Rectangle {
    int width, height;
public:
    Rectangle(int w, int h) : width(w), height(h) {}
    int area() { return width * height; }
};

enum Color { RED, GREEN, BLUE };
enum class Shape { CIRCLE, SQUARE, TRIANGLE };

3.4 Type Modifiers

unsigned int u = 10;   // cannot be negative
auto x = 42;              // compiler infers int
auto y = 3.14;            // compiler infers double

4. Operators

4.1 Arithmetic Operators

OperatorDescriptionExample
+Addition2 + 3 → 5
-Subtraction5 - 3 → 2
*Multiplication4 * 2 → 8
/Division8 / 2 → 4
%Modulus5 % 2 → 1
++Incrementi++ or ++i
--Decrementi-- or --i
Pre-increment (++i) can be slightly faster than post-increment (i++) in some contexts.

4.2 Comparison Operators

==, !=, <, >, <=, >=

4.3 Logical Operators

&&  // AND
||  // OR
!   // NOT

4.4 Bitwise Operators

&   // AND
|   // OR
^   // XOR
~   // NOT
<< // left shift
>> // right shift

4.5 Assignment Operators

=, +=, -=, *=, /=, %=

4.6 Miscellaneous Operators

condition ? expr1 : expr2   // ternary
sizeof(variable)              // size of variable
static_cast<type>(expr) // type casting

5. Tips for Staff-level Understanding

6. Suggested Practice

  1. Write small programs using all operator types
  2. Play with variable scope and lifetime
  3. Implement structs/classes like Point and Rectangle
  4. Experiment with pointers, references, auto, and constexpr