#4 Variables
Variables
In C++23, variables are containers for storing data values. Here are some key points and rules about variables in C++23:
### Types of Variables
– **int**: Stores integers (whole numbers), such as `123` or `-123`.
– **double**: Stores floating-point numbers, such as `19.99` or `-19.99`.
– **char**: Stores single characters, such as `’a’` or `’B’`.
– **string**: Stores text, such as `”Hello World”`.
– **bool**: Stores values with two states: `true` or `false`.
### Declaring Variables
To declare a variable, specify the type and assign it a value:
“`cpp
int myNum = 15;
“`
You can also declare a variable without assigning a value and assign it later:
“`cpp
int myNum;
myNum = 15;
“`
### Variable Rules
1. **Naming**: Variable names must start with a letter or underscore (`_`) and can contain letters, digits, and underscores.
2. **Case Sensitivity**: Variable names are case-sensitive (`myNum` and `mynum` are different).
3. **Scope**: Variables have a scope, which determines where they can be accessed. For example, variables declared inside a function are local to that function.
4. **Initialization**: It’s good practice to initialize variables when you declare them to avoid undefined behavior.
5. **Constants**: Use the `const` keyword to declare constants, which are variables whose values cannot be changed after initialization:
“`cpp
const int myConst = 10;
“`
### New Features in C++23
C++23 introduces several new features and improvements, including:
– **Explicit object parameter**: Allows specifying the object parameter explicitly in member functions.
– **Multidimensional subscript operator**: Enables using multiple indices in a subscript operator.
– **Static lambdas**: Allows defining lambdas as `static`.
– **New preprocessor directives**: Includes `#elifdef` and `#elifndef`.
– **Extended floating-point types**: Adds support for types like `std::float16_t`, `std::float32_t`, etc.
Memory and Variables
When you declare a variable in C++, you are essentially asking the system to allocate a portion of memory to store that variable’s value. The memory allocated for a variable depends on the type of data it holds, such as integers, floating-point numbers, characters, etc.
How Variables are Defined and Stored
Here’s a breakdown of the process:
-
Declaration and Definition: When you declare a variable, you specify its type and name. When you define it, you’re allocating the actual memory for it:
cppint myNum; // Declaration myNum = 10; // Definition (initialization)
-
Memory Allocation: The system allocates memory based on the type of the variable:
-
int: Typically occupies 4 bytes.
-
double: Typically occupies 8 bytes.
-
char: Typically occupies 1 byte.
-
-
Storage Classes: C++ provides different storage classes that determine the lifetime and visibility of a variable:
-
Automatic (auto): Default storage class for local variables, allocated on the stack.
-
Static (static): Retains value across multiple function calls, allocated in a fixed memory location.
-
External (extern): Used to declare a global variable that is defined in another file.
-
Use of Data Types
Data types define the type and size of data associated with variables. They also determine the operations that can be performed on these variables.
Basic Data Types:
-
int: Used for integers. Example:
int age = 25;
-
float and double: Used for floating-point numbers. Example:
float price = 19.99;
-
char: Used for single characters. Example:
char grade = 'A';
-
bool: Used for boolean values (
true
orfalse
). Example:bool isAdmin = true;
Derived Data Types:
-
Array: Collection of elements of the same type. Example:
int nums[5] = {1, 2, 3, 4, 5};
-
Pointer: Stores the memory address of another variable. Example:
int* ptr = &myNum;
-
Structure (struct): User-defined data type that groups different types. Example:
cppstruct Person { string name; int age; };
Relation to Memory Usage
Each data type has a specific size, which determines how much memory is allocated for it:
-
int: Typically 4 bytes.
-
double: Typically 8 bytes.
-
char: Typically 1 byte.
-
bool: Typically 1 byte.
Memory Layout
Variables are stored in memory in different sections:
-
Stack: Stores local variables and function call information.
-
Heap: Used for dynamic memory allocation, accessed via pointers.
-
Static/Global: Stores global and static variables.
Here’s a simple example to illustrate:
// Ex02.cpp - Variables and Memory
import std;
int main()
{
int num = {42};
double* ptr; // Pointer to allocate memory on the heap
ptr = new double; // Dynamic allocation
*ptr = 3.14;
std::println("num: {} ", num);
std::print("*ptr: {} \n", *ptr);
delete ptr; // Free the allocated memory
return 0;
}
In this example:
-
num
is stored on the stack. -
ptr
points to a memory location on the heap where the value3.14
is stored.
Variable Storage on Stack
When you declare a local variable like int num = 42;
inside a function, the following happens:
-
Function Call: When the function is called, a new stack frame is created. This frame contains all the local variables and bookkeeping information (like return address, etc.).
-
Memory Allocation: The variable
num
is allocated space within this stack frame. In this case, sincenum
is anint
, typically 4 bytes are reserved for it. -
Initialization: The value
42
is stored in the allocated memory fornum
.
Push-Pop Mechanism
Even though the stack uses a push-pop mechanism, this is abstracted away when you work with local variables:
-
Push: When you enter a function and declare local variables, they are “pushed” onto the stack as part of the stack frame.
-
Pop: When the function exits, the stack frame is “popped” off the stack, and all local variables are deallocated.
ASSEMBLY Language Compare
C++ 23 does a lot for you unlike languages like Assembly. In assembly to get the variable on the stack you would need to push that value on and then pop it when you are getting ready to consume or deallocate it. In C++ the creation of the function does all of this for you.