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: Using Integer Types for Variable Declaration
#include <iostream> // Provides std::cout, std::endl
#include <limits> // For std::numeric_limits to get type properties (e.g., min/max values)
int main() {
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;
return 0;
}
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