Home

#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:

  1. 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)
  2. 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.
  3. 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:

Derived Data Types:

Relation to Memory Usage

Each data type has a specific size, which determines how much memory is allocated for it:

Memory Layout

Variables are stored in memory in different sections:

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:

Variable Storage on Stack

When you declare a local variable like int num = 42; inside a function, the following happens:

  1. 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.).
  2. Memory Allocation: The variable num is allocated space within this stack frame. In this case, since num is an int, typically 4 bytes are reserved for it.
  3. Initialization: The value 42 is stored in the allocated memory for num.

Push-Pop Mechanism

Even though the stack uses a push-pop mechanism, this is abstracted away when you work with local variables:

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.