C++:C++ Variables and Primitive Data Types with Examples
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:

ParameterTypeDescription
typeData Typeint, float, double, char, bool, or auto.
variable_nameIdentifierName of the variable.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler