Variables & Constants
C++ is a strongly and statically-typed programming language. Variables must be declared with a specific data type before they are used, allocating concrete space on stack memory frames.
1 Primitive Data Types & Conversions
C++ contains the standard numerical data primitives:
- `bool` (1 byte): Stores `true` or `false`.
- `char` (1 byte): Stores single character codes.
- `int` (4 bytes): Stores standard integers.
- `float` (4 bytes): Single-precision floating point.
- `double` (8 bytes): Double-precision floating point (default decimals).
Casting: Avoid implicit casting when possible. Use C++ style **`static_cast<type>(val)`** rather than parenthetical C-style casting: `double avg = static_cast<double>(score) / total;`.
2 Variables & Constants Codes
Let's run a program declaring types, casting, and defining constant flags:
C++ — Variables and Casting
▶ Run Code
#include <iostream>
int main() {
int age = 22;
double price = 49.99;
const double TAX_RATE = 0.08; // Cannot be modified later
// Explicit static cast to double
int score = 45;
int total = 50;
double percentage = static_cast<double>(score) / total * 100;
std::cout << "Age: " << age << "\n";
std::cout << "Score Percentage: " << percentage << "%" << "\n";
std::cout << "Tax Rate: " << TAX_RATE << "\n";
return 0;
}
3 Code Challenge
Challenge: Declare a `const` float variable representing gravity (`9.8f`). Try to reassign its value to `9.81f` inside your code, compile it, observe the compiler error message, and then fix it by removing the invalid assignment statement.