Crash Courses · Basic
Variables, Types, Pointers & References
Static types, raw memory access, and safer C++ references
35 min read+160 XP on completionCert: C++ Crash Course
Tap any word in the text below to start reading from there.
Variables, Types, Pointers & References
Fundamental Types
#include <iostream>
int main() {
int i = 42;
double d = 3.14;
char c = 'A';
bool b = true;
float f = 2.71f; // f suffix = float literal
long l = 1000000L;
// C++11 auto type deduction
auto x = 5; // int
auto y = 3.14; // double
auto z = "hello"; // const char*
std::cout << i << " " << d << " " << c << std::endl;
return 0;
}const
const int MAX = 100; // compile-time constant
const double PI = 3.14159;
// const parameter — function cannot modify it
void print(const std::string& s) {
std::cout << s << std::endl;
}Pointers
int x = 10;
int* p = &x; // p holds the address of x
std::cout << p << std::endl; // address: 0x7fff...
std::cout << *p << std::endl; // dereference: 10
*p = 20; // modify x through pointer
std::cout << x; // 20
int* null_ptr = nullptr; // null pointer (C++11)References
A reference is an alias — it must be initialized and always refers to the same variable:
int a = 5;
int& ref = a; // ref IS a (not a copy)
ref = 10;
std::cout << a; // 10 — a was changed through ref
// References are the preferred way to pass large objects
void increment(int& n) {
n++;
}
int main() {
int val = 7;
increment(val);
std::cout << val; // 8
}Pointer vs Reference
| Pointer | Reference | |
|---|---|---|
| Can be null | Yes | No |
| Can be reseated | Yes | No |
| Syntax to access | *p or p-> | r directly |
| Use when | Nullable or reseat needed | Simple alias / function param |
const with Pointers
int x = 5, y = 10;
const int* p1 = &x; // pointer to const: can't change *p1
int* const p2 = &x; // const pointer: can't change p2 itself
const int* const p3 = &x; // both const
p1 = &y; // ok — pointer can change
// *p1 = 9; // ERROR — can't modify through const pointersizeof and size_t
#include <cstddef>
std::cout << sizeof(int) << " bytes\n"; // 4
std::cout << sizeof(double) << " bytes\n"; // 8
std::cout << sizeof(char) << " bytes\n"; // 1
size_t n = 42; // use for sizes and indicesReading progress
0% read
In this module
Reference (&)
Pointer (*)
const
nullptr
0%