Variables and types
C++ is statically typed: every variable has a type, fixed when it's declared.
| Type | Holds | Example |
|---|---|---|
int | whole numbers | int lives = 3; |
double | decimal numbers | double price = 19.99; |
char | one character | char grade = 'A'; |
bool | true or false | bool done = false; |
C++
#include <iostream>
using namespace std;
int main() {
int lives = 3;
double price = 19.99;
char grade = 'A';
bool gameOver = false;
cout << "Lives: " << lives << endl;
cout << "Price: " << price << endl;
cout << "Grade: " << grade << endl;
cout << "Game over? " << gameOver << endl;
return 0;
}cout prints false as 0 and true as 1.
Changing values
C++
#include <iostream>
using namespace std;
int main() {
int score = 10;
score += 5; // 15
score *= 2; // 30
score--; // 29
cout << score << endl;
return 0;
}Integer and decimal division
C++
#include <iostream>
using namespace std;
int main() {
int a = 7, b = 2;
cout << a / b << endl; // 3: integer division
cout << a % b << endl; // 1: remainder
cout << (double)a / b << endl; // 3.5
cout << 7.0 / 2 << endl; // 3.5
return 0;
}Constants
C++
#include <iostream>
using namespace std;
int main() {
const double PI = 3.14159;
const int DAYS_IN_WEEK = 7;
cout << "Circle area (r=3): " << PI * 3 * 3 << endl;
cout << "Hours in a week: " << DAYS_IN_WEEK * 24 << endl;
return 0;
}Constants are conventionally written in UPPER_CASE.
auto
Modern C++ can work out a variable's type from its value:
C++
auto count = 10; // int
auto ratio = 0.75; // double
auto letter = 'x'; // charauto is handy with long type names; for simple variables, writing the type is clearer.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.