Page Content

Tutorials

Variable Declaration And Initialization In C++ With Code

Variable Declaration and Initialization in C++

Types, C++ fundamentals, define a data element’s contents and operations. The compiler can help you write safer and more effective code since C++ is highly typed and requires you to declare variable types before using them. The compiler needs the variable type to determine how much memory to allocate and initialise it.

The primitive built-in types defined by C++ include a unique void type and arithmetic types (characters, integers, boolean values, and floating-point numbers).

Variable Declaration and Definition

Your programs can work with named storage that is provided by a variable. The types of variables dictate their memory layout and size, the range of values they may store, and the operations that can be performed on them. Programmers that use C++ frequently use the phrases “variable” and “object” interchangeably. An object is a typed region of memory.

There is a little but significant difference between a definition and a declaration:

  • A declaration affirms the existence of a variable and provides its name and type.
  • A definition is a declaration that grants storage for the variable and may also provide it an initial value, in addition to defining its name and type.
    • A definition can be defined as any declaration that contains an explicit initialiser.
    • You must not supply an explicit initialiser and use the extern keyword to get a declaration that is not also a definition.

Syntax for Variable Definition

A type specifier comes first, then one or more variable names segregated by commas, and finally a semicolon to complete a simple variable definition.

  • type variable_list;
  • In a single line, you can declare several variables of the same type, separated by commas.

Variable placement is possible in C++ anywhere a statement is allowed, usually close to the variable’s initial use. This makes it simpler to give a helpful starting value and enhances readability. The scope of variables is restricted to the if, switch, while, and for statements; they can also be defined inside the control structure of those statements.

Variable Initialization

Assigning a value to an object at the time of creation is known as initialisation. In contrast, assignment replaces an object’s existing value with a new one, erasing the old one. For built-in types, initialising a variable before using it is essential since uninitialised local variables are a typical source of issues and will have undefined (junk) values.

Default Initialization

  • The initial value of built-in type objects defined at global scope is set to 0 automatically.
  • The built-in local static variables are also initialised to 0 in the absence of an explicit initialiser.
  • Uninitialised and having undefined values if not explicitly initialised are objects of built-in type specified at local scope (non-static local variables).

Ways to Initialize Built-in Types

Assignment Initialization: The equals sign (=) is used.

Direct Initialization (Function Syntax): surrounding the initial value with brackets ().

List Initialization (Uniform Initialization): Introduced in C++11, one or more initialisers are enclosed in curly brackets {}. When declaring a named type, this is the preferable method.

Calling a Constructor: This syntax can theoretically be used for built-in types as well, albeit it is more applicable to user-defined types (classes).

Example

#include <iostream> // Provides std::cout, std::cin, std::endl 
#include <string>   // Provides std::string for textual data 
#include <limits>   // For std::numeric_limits to get type properties (e.g., min/max values)
// Global variables are automatically initialized to zero or equivalent if not explicitly initialized 
int global_int;           // Declaration and definition, default initialized to 0
std::string global_string; // Declaration and definition, default initialized to an empty string
int main() {
    // --- Integer Types (int, short, long, long long, unsigned variants) ---
    // Used for whole numbers [98, 99]
    std::cout << "--- Integer Types ---" << std::endl;
    // 1. int: Most natural size for the machine, typically 32-bit
    int count = 25;           // Assignment initialization 
    int quantity(50);         // Direct initialization (function syntax) 
    int total_items {75};     // List initialization (C++11) 
    std::cout << "int variables: count = " << count << ", quantity = " << quantity << ", total_items = " << total_items << std::endl;
    std::cout << "Size of int: " << sizeof(int) << " bytes" << std::endl;
    std::cout << "Range of int: " << std::numeric_limits<int>::min() << " to " << std::numeric_limits<int>::max() << std::endl;
    // 2. unsigned int: Stores only non-negative values (0 and positive)
    unsigned int page_views = 100000;
    std::cout << "unsigned int page_views = " << page_views << std::endl;
    std::cout << "Size of unsigned int: " << sizeof(unsigned int) << " bytes" << std::endl;
    // 3. short: Typically smaller than int (e.g., 2 bytes) 
    short year = 2024;
    std::cout << "short year = " << year << std::endl;
    std::cout << "Size of short: " << sizeof(short) << " bytes" << std::endl;
    // 4. long: Guaranteed to be at least 32 bits 
    long file_size = 2147483647L; // 'L' suffix for long literal
    std::cout << "long file_size = " << file_size << std::endl;
    std::cout << "Size of long: " << sizeof(long) << " bytes" << std::endl;
    // 5. long long: Guaranteed to be at least 64 bits (C++11)
    long long large_id = 987654321LL; // 'LL' suffix for long long literal
    std::cout << "long long large_id = " << large_id << std::endl;
    std::cout << "Size of long long: " << sizeof(long long) << " bytes" << std::endl;
    std::cout << "\n--- Floating-Point Types ---" << std::endl;
    // --- Floating-Point Types (float, double, long double) ---
    // Used for numbers with fractional parts [99]
    // 1. float: Single-precision floating-point, 'f' suffix for literal
    float current_temp = 23.5f;
    std::cout << "float current_temp = " << current_temp << std::endl;
    std::cout << "Size of float: " << sizeof(float) << " bytes" << std::endl;
    // 2. double: Double-precision floating-point, default for floating-point literals 
    double speed_of_light = 299792458.0;
    std::cout << "double speed_of_light = " << speed_of_light << std::endl;
    std::cout << "Size of double: " << sizeof(double) << " bytes" << std::endl;
    // 3. long double: Extended-precision floating-point, 'L' suffix for literal 
    long double astronomical_unit = 1.495978707e11L;
    std::cout << "long double astronomical_unit = " << astronomical_unit << std::endl;
    std::cout << "Size of long double: " << sizeof(long double) << " bytes" << std::endl;
    std::cout << "\n--- Boolean Type ---" << std::endl;
    // --- Boolean Type (bool) ---
    // Represents logical truth values: true or false 
    bool is_logged_in = true; // 'true' is a boolean literal
    bool has_error = false;   // 'false' is a boolean literal
    std::cout << "is_logged_in = " << is_logged_in << " (usually displays as 1)" << std::endl;
    std::cout << "has_error = " << has_error << " (usually displays as 0)" << std::endl;
    std::cout << "Size of bool: " << sizeof(bool) << " bytes" << std::endl;
    // To display bool as "true" or "false"
    std::cout << std::boolalpha;
    std::cout << "is_logged_in (boolalpha) = " << is_logged_in << std::endl;
    std::cout << std::noboolalpha; // Revert to numeric output
    std::cout << "\n--- Character Type ---" << std::endl;
    // --- Character Type (char) ---
    // Represents a single character, typically 1 byte 
    char grade = 'A';             // Character literal enclosed in single quotes 
    char symbol = '$';
    char newline = '\n';          // Escape sequence for newline 
    char tab = '\t';              // Escape sequence for tab
    std::cout << "Character variables: grade = " << grade << ", symbol = " << symbol << std::endl;
    std::cout << "Newline character: " << newline << "Tab character: " << tab << " (visible as indentation)" << std::endl;
    std::cout << "Size of char: " << sizeof(char) << " bytes" << std::endl;
    std::cout << "\n--- std::string (Library Type for Strings) ---" << std::endl;
    // --- String Literals and std::string (Library Type, not built-in, but commonly used with char) ---
    // String literals are sequences of characters in double quotes, automatically null-terminated 
    std::string message = "Hello, C++!"; // Copy initialization from a string literal 
    std::string greeting("Hi there!");   // Direct initialization 
    std::string empty_string;            // Default initialization (creates an empty string) 
    std::cout << "String message: " << message << std::endl;
    std::cout << "String greeting: " << greeting << std::endl;
    std::cout << "Empty string (should show nothing): " << empty_string << std::endl;
    // --- Void Type ---
    // Cannot define a variable of type void 
    // void anything; // This would cause a compilation error.
    // Example of using local variables which are uninitialized if not explicit
    int local_uninitialized_int;
    // Attempting to use local_uninitialized_int here without initialization would be undefined behavior 
    // std::cout << "Uninitialized local int: " << local_uninitialized_int << std::endl; // DANGER!
    local_uninitialized_int = 99; // Now it's assigned a value.
    std::cout << "Initialized local int after assignment: " << local_uninitialized_int << std::endl;
    std::cout << "\nGlobal int value (default initialized): " << global_int << std::endl;
    std::cout << "Global string value (default initialized): \"" << global_string << "\"" << std::endl;
    return 0; // Indicates successful program execution 
}

Output

--- Integer Types ---
int variables: count = 25, quantity = 50, total_items = 75
Size of int: 4 bytes
Range of int: -2147483648 to 2147483647
unsigned int page_views = 100000
Size of unsigned int: 4 bytes
short year = 2024
Size of short: 2 bytes
long file_size = 2147483647
Size of long: 8 bytes
long long large_id = 987654321
Size of long long: 8 bytes
--- Floating-Point Types ---
float current_temp = 23.5
Size of float: 4 bytes
double speed_of_light = 2.99792e+08
Size of double: 8 bytes
long double astronomical_unit = 1.49598e+11
Size of long double: 16 bytes
--- Boolean Type ---
is_logged_in = 1 (usually displays as 1)
has_error = 0 (usually displays as 0)
Size of bool: 1 bytes
is_logged_in (boolalpha) = true
--- Character Type ---
Character variables: grade = A, symbol = $
Newline character: 
Tab character: 	 (visible as indentation)
Size of char: 1 bytes
--- std::string (Library Type for Strings) ---
String message: Hello, C++!
String greeting: Hi there!
Empty string (should show nothing): 
Initialized local int after assignment: 99
Global int value (default initialized): 0
Global string value (default initialized): ""
Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index