C++C++ · Lesson 2 of 9
Variables & Types
C++ inherits all of C's types and adds a bunch of its own. The good news: you'll mostly use int, double, string, and bool.
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
// Fundamental types (same as C)
int i = 42;
double d = 3.14159;
float f = 3.14f;
bool b = true;
char c = 'A';
long long ll = 1234567890LL;
// C++ adds: string (not a char array)
string name = "Alice"; // no buffer size needed
string greeting = "Hello, " + name + "!"; // concatenation with +
cout << greeting << "
";
cout << "Length: " << name.length() << "
"; // 5
// auto — type inference (C++11)
auto x = 42; // int
auto y = 3.14; // double
auto z = "hello"; // const char*
auto s = string("hello"); // std::string
// const
const int MAX = 100;
const double PI = 3.14159265358979;
// References — alias for another variable
int original = 10;
int& ref = original; // ref IS original
ref = 99;
cout << original << "
"; // 99 — original changed through ref
cout << i << " " << d << " " << b << "
";
return 0;
}C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
// std::vector — dynamic array (the C++ way to use arrays)
vector<int> nums = {1, 2, 3, 4, 5};
nums.push_back(6);
nums.pop_back();
cout << nums[0] << "
"; // 1
cout << nums.size() << "
"; // 5
cout << nums.front() << "
"; // 1
cout << nums.back() << "
"; // 5
// Range-based for loop (C++11)
for (int n : nums) {
cout << n << " ";
}
cout << "
";
// Vector of strings
vector<string> fruits = {"apple", "banana", "cherry"};
fruits.push_back("date");
for (const string& f : fruits) { // const& to avoid copying
cout << f << "
";
}
return 0;
}