C++•Variables
C++ Variables and Primitive Data Types with Examples
C++ is a statically-typed, compiled language. Variables must be declared with a specific type or auto for compiler inference.
Syntax
type variable_name = initial_value;
auto deduced_variable = value;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| type | Data Type | int, float, double, char, bool, or auto. |
| variable_name | Identifier | Name of the variable. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C++ locally:
#include <iostream>
#include <iomanip>
#include <string>
int main() {
std::string appName = "Compilra Engine";
int activeNodes = 12;
double cpuUtilization = 48.75;
bool isClusterHealthy = true;
std::cout << "Application: " << appName << "\n";
std::cout << "Active Nodes: " << activeNodes << "\n";
std::cout << "CPU Usage: " << std::fixed << std::setprecision(1) << cpuUtilization << "%\n";
std::cout << "System Status: " << (isClusterHealthy ? "ONLINE" : "OFFLINE") << "\n";
return 0;
}Expected Output:
Application: Compilra Engine Active Nodes: 12 CPU Usage: 48.8% System Status: ONLINE
How It Works: Step-by-Step
- Lines 6-9: Declares typed variables for string, integer, double, and boolean.
- Lines 11-14: Outputs values to standard output using std::cout and stream insertion operators.
Key Concepts
- In C++, every variable has a fixed memory size and type determined at compile time.
- std::cout is the standard output stream object from <iostream>.
- The auto keyword allows the compiler to deduce the variable type from its initializer.
Common Mistake: Using uninitialized local variables
In C++, uninitialized local variables contain garbage values from whatever was previously in that memory.
❌ Incorrect
int total; std::cout << total; // Prints unpredictable garbage memory!
✅ Correct
int total = 0; std::cout << total; // Guaranteed 0
Related C++ Tutorials & Compiler
C++ Operators: Arithmetic, Relational, and Bitwise
Master C++ arithmetic, comparison, logical, compound assignment, and bitwise operators.
C++ Input and Output: std::cin, std::cout, and getline
Learn how to read from stdin with std::cin and std::getline, and format output stream data.
C++ Type Casting: static_cast and Modern C++ Casts
Master compile-time type conversion using static_cast and understand modern C++ casting operators.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.