C++ Tutorial
C++ Variables
A variable has a type, a name, and a value. Declare the type first: int count = 3;
Declare the type first
A variable is a named box in memory. In C++ you state the type before the name. The compiler then knows how much space to reserve and which operations are allowed. This is unlike Python, where a name appears when you assign to it.
Example
#include <iostream>
using namespace std;
int main() {
int count = 3;
cout << count << endl;
return 0;
}int is the type. count is the name. 3 is the value. The semicolon ends the statement.
Try the examples at /cpp/try. That editor compiles with g++.
Assignment changes the value
After a variable exists, = stores a new value of a compatible type. The old value is gone. You can declare without a value and assign later — but you must assign before you read, or the program has undefined behavior.
Example
#include <iostream>
using namespace std;
int main() {
int score = 0;
score = 10;
score = score + 5;
cout << score << endl;
return 0;
}Do not print a variable you never initialized. Always give a starting value, even if that value is0.
const does not change
Put const before the type when the value must stay fixed. The compiler rejects any later assignment. Use it for names that are really facts: a tax rate, a maximum, a conversion factor.
Example
#include <iostream>
using namespace std;
int main() {
const int days_in_week = 7;
int weeks = 3;
cout << weeks * days_in_week << endl;
return 0;
}Writing days_in_week = 8; after that declaration is an error. That is the point ofconst.
Several variables at once
You can list more than one name after a type, separated by commas. Each name can have its own initializer. Keep the list short. Three related integers on one line is fine. A mixed grab bag is harder to read.
Example
int x = 1, y = 2, z = 3;
double width = 4.5, height = 2.0;
cout << x + y + z << endl;
cout << width * height << endl;Names
Choose names that say what the value is. C++ is case-sensitive: Count is not count. Start with a letter or underscore. Do not use a keyword such as int or return.
| Good | Poor |
|---|---|
item_count, taxRate, n | x1x2, data, temp2 with no context |
Type stays put
An int stays an int. You cannot store a whole sentence in it. You cannot later turn the same name into a double by assigning 3.14 and expecting a new type. Pick the type that matches the data, then keep using that name for that kind of value.
Next: reading values from the keyboard into those variables.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.
Physics
Average speed on a road
Average speed is total distance over total time. A car that covers 150 km in 2.5 h was doing 60 km/h on average. That is not the speedometer at every instant.
Store distance and time in separate names, then divide. One box called result hides which quantity went wrong when the answer looks odd.
v_avg = Δs / Δt
Example
#include <iostream>
using namespace std;
int main() {
double distance_km = 150.0;
double time_h = 2.5;
double speed = distance_km / time_h;
cout << "v = " << speed << " km/h" << endl;
return 0;
}Biology
Resting pulse
Heart rate is reported in beats per minute. Counting for 15 s and multiplying by 4 is the usual shortcut. 18 beats in 15 s is 72 bpm, a normal resting value for many adults.
The name bpm is the unit. A bare 72 in a file could be age, mass, or a mark out of 100.
bpm = beats_in_15s × 4
Exercise, caffeine, and fever all raise the number. Resting rate is measured sitting, after a few minutes still.
Example
#include <iostream>
using namespace std;
int main() {
int beats_in_15s = 18;
int bpm = beats_in_15s * 4;
cout << "resting heart rate = " << bpm << " bpm" << endl;
return 0;
}