C++

Variables and Constants in C++

In C++, data is the core of every program. To process this data, we need a way to store it in the computer's memory. This is where Variables and Constants come into play. Theoretically, they are names given to a memory location that the program can manipulate.

1. The Theory: Memory and Identifiers

When you declare a variable or constant, the Operating System reserves a specific "mailbox" in the RAM.

  • The Address: Every memory location has a hexadecimal address (e.g., 0x7ffeb).

  • The Identifier: Since humans cannot easily remember hexadecimal addresses, we use Identifiers (names like age or price) to refer to those locations.

  • The Data Type: This defines the size of the "mailbox" (e.g., 4 bytes for an integer) and the type of data it can hold.

2. Variables in C++

A Variable is an identifier whose value can change during the execution of the program.

A. Declaration and Initialization

In C++, you must declare a variable before using it. This is a "strongly typed" requirement.

  • Declaration: int score; (Reserves memory but contains a random "garbage" value).

  • Initialization: score = 100; (Assigns a value to the reserved memory).

  • Combined: int score = 100;

B. Naming Rules (Identifiers)

To write valid C++ code, identifiers must follow these theoretical constraints:

  1. Must begin with a letter (a-z, A-Z) or an underscore (_).

  2. Cannot start with a digit.

  3. Can only contain letters, digits, and underscores.

  4. Case Sensitivity: myValue and myvalue are two completely different memory locations.

  5. Cannot use Keywords (like int, return, class) because they have pre-defined meanings for the compiler.

3. Constants in C++

A Constant is an identifier whose value cannot be modified once it is initialized. Attempting to change a constant will result in a compile-time error.

A. The const Keyword

This is the modern C++ way to define constants. It obeys scope rules and is typed.

  • Theory: When the compiler sees const, it places the variable in a read-only segment of memory or replaces its occurrences with the value during optimization.

  • Example: const float PI = 3.14159;

B. The #define Preprocessor (Macros)

This is a legacy method inherited from C.

  • Theory: This doesn't actually create a variable. Instead, the Preprocessor scans the code before compilation and physically replaces every instance of the name with the value. It has no data type and does not follow scope rules.

  • Example: #define MAX_USERS 100 (Note: no semicolon or equals sign).

C. Literal Constants

These are values typed directly into the code, such as 10, 3.14, or "Hello". They don't have a name and exist only in the instruction itself.

4. Practical Code Example


#include <iostream>
using namespace std;

// Using Preprocessor Constant
#define GRAVITY 9.8 

int main() {
    // Variable declaration and initialization
    int speed = 0; 
    
    // Constant declaration
    const int MAX_SPEED = 120;

    cout << "Starting speed: " << speed << endl;

    // Modifying the variable
    speed = 60; 
    cout << "Updated speed: " << speed << endl;

    // Using constants in a calculation
    cout << "Gravity constant: " << GRAVITY << endl;
    cout << "Speed limit: " << MAX_SPEED << endl;

    // MAX_SPEED = 150; // UNCOMMENTING THIS WILL CAUSE A COMPILER ERROR

    return 0;
}

5. Theoretical Differences: Variable vs. Constant

FeatureVariableConstant (const)
Value ChangeCan be updated anytime.Immutable after initialization.
InitializationOptional at declaration.Mandatory at declaration.
Memory AccessRead and Write.Read-Only.
PurposeStoring changing data (counters, inputs).Fixing "Magic Numbers" (PI, tax rates).

6. Scope of Variables (Long Theory)

Variables also have a property called Scope, which defines where in the code the variable is "alive."

  1. Local Variables: Declared inside a function or a block { }. They are created on the Stack when the block starts and destroyed when it ends.

  2. Global Variables: Declared outside all functions. They exist in the Data Segment and stay alive for the entire duration of the program.

    • Theoretical Warning: Excessive use of global variables makes code hard to debug because any function can change their value unexpectedly.

  3. Static Variables: Declared with the static keyword. They are local in scope but "remember" their value between function calls because they are stored in the Data Segment rather than the Stack.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now